rpc.go 5.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267
  1. // Author: NiuJiuRu
  2. // Email: niujiuru@qq.com
  3. package jsonrpc2
  4. import (
  5. "encoding/json"
  6. "errors"
  7. "fmt"
  8. )
  9. type ErrCode int
  10. const (
  11. ErrParse ErrCode = -32700 // "Parse error"
  12. ErrInvalidRequest ErrCode = -32600 // "Invalid request"
  13. ErrMethodNotFound ErrCode = -32601 // "Method not found"
  14. ErrInvalidParams ErrCode = -32602 // "Invalid params"
  15. ErrInternal ErrCode = -32603 // "Internal error"
  16. )
  17. type Error struct {
  18. Code ErrCode `json:"code"` //// 错误码
  19. Message string `json:"message"` //// 错误信息
  20. }
  21. func (e Error) Error() string {
  22. return e.Message
  23. }
  24. var errMessages = map[ErrCode]string{
  25. ErrParse: "Parse error", // 解析错误
  26. ErrInvalidRequest: "Invalid request", // 无效请求
  27. ErrMethodNotFound: "Method not found", // 无效方法
  28. ErrInvalidParams: "Invalid params", // 无效参数
  29. ErrInternal: "Internal error", // 内部错误
  30. }
  31. type Request struct {
  32. JSONRPC string `json:"jsonrpc"` // 版本号, 固定: "2.0"
  33. Method string `json:"method"` // 调用方法, 执行函数名
  34. Params json.RawMessage `json:"params,omitempty"` // 请求参数, 可选可为空
  35. ID *int `json:"id,omitempty"` // 请求ID, 用于标识请求
  36. }
  37. type Response struct {
  38. JSONRPC string `json:"jsonrpc"` // 版本号, 固定: "2.0"
  39. Result json.RawMessage `json:"result,omitempty"` // 响应结果, 可选可为空
  40. Error *Error `json:"error,omitempty"` // 错误信息, 可选可为空
  41. ID *int `json:"id"` // 应答ID, 响应匹配请求
  42. }
  43. // 解析请求数据
  44. func ParseRequest(input any) (*Request, error) {
  45. var raw []byte
  46. switch v := input.(type) {
  47. case nil:
  48. return nil, errors.New("input is nil")
  49. case string:
  50. raw = []byte(v)
  51. case []byte:
  52. raw = v
  53. default:
  54. return nil, errors.New("unsupported input type: must be string or []byte")
  55. }
  56. var req Request
  57. if err := json.Unmarshal(raw, &req); err != nil {
  58. return nil, fmt.Errorf("unmarshal request: %w", err)
  59. }
  60. if req.JSONRPC != "2.0" {
  61. return nil, errors.New(`"jsonrpc" must be "2.0"`)
  62. }
  63. return &req, nil
  64. }
  65. // 解析应答数据
  66. func ParseResponse(input any) (*Response, error) {
  67. var raw []byte
  68. switch v := input.(type) {
  69. case nil:
  70. return nil, errors.New("input is nil")
  71. case string:
  72. raw = []byte(v)
  73. case []byte:
  74. raw = v
  75. default:
  76. return nil, errors.New("unsupported input type: must be string or []byte")
  77. }
  78. var resp Response
  79. if err := json.Unmarshal(raw, &resp); err != nil {
  80. return nil, fmt.Errorf("unmarshal response: %w", err)
  81. }
  82. if resp.JSONRPC != "2.0" {
  83. return nil, errors.New(`"jsonrpc" must be "2.0"`)
  84. }
  85. // 情况 1:result 和 error 同时为空 → 错误
  86. if resp.Error == nil && resp.Result == nil {
  87. return nil, errors.New(`response must contain either "result" or "error" field`)
  88. }
  89. // 情况 2:result 和 error 同时存在 → 错误
  90. if resp.Error != nil && resp.Result != nil {
  91. return nil, errors.New(`response can't contain both "result" and "error" field`)
  92. }
  93. // 情况 3:成功时的应答 → 必须有id&且不能空
  94. if resp.Result != nil {
  95. if resp.ID == nil {
  96. return nil, errors.New(`"id" must exist and cannot be null for successful response`)
  97. }
  98. return &resp, nil
  99. }
  100. // 情况 4:错误时的应答 → 必须有id&且不能空
  101. if resp.Error.Code == ErrParse { // 特例: Parse error (-32700)时
  102. return &resp, nil
  103. }
  104. if resp.ID == nil {
  105. return nil, errors.New(`"id" must exist and cannot be null for error response`)
  106. }
  107. return &resp, nil
  108. }
  109. // 编码JSON数据
  110. func marshalJSON(input any) (json.RawMessage, error) {
  111. switch v := input.(type) {
  112. case nil:
  113. return nil, nil
  114. case []byte:
  115. return nil, errors.New("[]byte is not allowed: use json.RawMessage for raw JSON")
  116. case json.RawMessage:
  117. return v, nil
  118. default:
  119. b, err := json.Marshal(v)
  120. if err != nil {
  121. return nil, fmt.Errorf("marshal json: %w", err)
  122. }
  123. return json.RawMessage(b), nil
  124. }
  125. }
  126. // 构建一个请求
  127. func BuildRequest(method string, params any, id ...int) (*Request, error) {
  128. if method == "" {
  129. return nil, errors.New("method must be non-empty")
  130. }
  131. raw, err := marshalJSON(params)
  132. if err != nil {
  133. return nil, err
  134. }
  135. var rid int
  136. if len(id) > 0 {
  137. rid = id[0]
  138. } else {
  139. rid = nextID()
  140. }
  141. req := &Request{
  142. JSONRPC: "2.0",
  143. Method: method,
  144. ID: &rid,
  145. }
  146. if raw != nil { // 非空参数
  147. req.Params = raw
  148. }
  149. return req, nil
  150. }
  151. // 构建一个通知
  152. func BuildNotification(method string, params any) (*Request, error) {
  153. if method == "" {
  154. return nil, errors.New("method must be non-empty")
  155. }
  156. raw, err := marshalJSON(params)
  157. if err != nil {
  158. return nil, err
  159. }
  160. req := &Request{
  161. JSONRPC: "2.0",
  162. Method: method,
  163. }
  164. if raw != nil { // 非空参数
  165. req.Params = raw
  166. }
  167. return req, nil
  168. }
  169. // 构建成功应答
  170. func BuildResult(req *Request, result any) (*Response, error) {
  171. if req.ID == nil { // 通知类型, 不用应答
  172. return nil, nil
  173. }
  174. raw, err := marshalJSON(result)
  175. if err != nil {
  176. return nil, err
  177. }
  178. if raw == nil {
  179. raw = json.RawMessage("null")
  180. }
  181. return &Response{
  182. JSONRPC: "2.0",
  183. Result: raw,
  184. ID: req.ID,
  185. }, nil
  186. }
  187. // 构建错误应答
  188. func BuildError(req *Request, code ErrCode, message string) *Response {
  189. id := (*int)(nil)
  190. if req != nil {
  191. id = req.ID
  192. }
  193. emsg := message
  194. if emsg == "" {
  195. emsg = errMessages[code]
  196. }
  197. return &Response{
  198. JSONRPC: "2.0",
  199. Error: &Error{
  200. Code: code,
  201. Message: emsg,
  202. },
  203. ID: id,
  204. }
  205. }
  206. // 请求转字符串
  207. func (req *Request) String() (string, error) {
  208. b, err := json.Marshal(req)
  209. if err != nil {
  210. return "", fmt.Errorf("marshal request: %w", err)
  211. }
  212. return string(b), nil
  213. }
  214. // 应答转字符串
  215. func (resp *Response) String() (string, error) {
  216. b, err := json.Marshal(resp)
  217. if err != nil {
  218. return "", fmt.Errorf("marshal response: %w", err)
  219. }
  220. return string(b), nil
  221. }