rpc.go 5.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271
  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. if req.Method == "" {
  64. return nil, errors.New("method must be non-empty")
  65. }
  66. return &req, nil
  67. }
  68. // 解析应答数据
  69. func ParseResponse(input any) (*Response, error) {
  70. var raw []byte
  71. switch v := input.(type) {
  72. case nil:
  73. return nil, errors.New("input is nil")
  74. case string:
  75. raw = []byte(v)
  76. case []byte:
  77. raw = v
  78. default:
  79. return nil, errors.New("unsupported input type: must be string or []byte")
  80. }
  81. var resp Response
  82. if err := json.Unmarshal(raw, &resp); err != nil {
  83. return nil, fmt.Errorf("unmarshal response: %w", err)
  84. }
  85. if resp.JSONRPC != "2.0" {
  86. return nil, errors.New(`"jsonrpc" must be "2.0"`)
  87. }
  88. // 情况 1:result 和 error 同时为空 → 错误
  89. if resp.Error == nil && resp.Result == nil {
  90. return nil, errors.New(`response must contain either "result" or "error" field`)
  91. }
  92. // 情况 2:result 和 error 同时存在 → 错误
  93. if resp.Error != nil && resp.Result != nil {
  94. return nil, errors.New(`response can't contain both "result" and "error" field`)
  95. }
  96. // 情况 3:成功时的应答 → 必须有id&且不能空
  97. if resp.Result != nil {
  98. if resp.ID == nil {
  99. return nil, errors.New(`"id" must exist and cannot be null for successful response`)
  100. }
  101. return &resp, nil
  102. }
  103. // 情况 4:错误时的应答 → 必须有id&且不能空
  104. if resp.Error.Code == ErrParse { // 特例: Parse error (-32700)时
  105. return &resp, nil
  106. }
  107. if resp.ID == nil {
  108. return nil, errors.New(`"id" must exist and cannot be null for error response`)
  109. }
  110. return &resp, nil
  111. }
  112. // 编码JSON数据
  113. func marshalJSON(input any) (json.RawMessage, error) {
  114. switch v := input.(type) {
  115. case nil:
  116. return nil, nil
  117. case []byte:
  118. return nil, errors.New("[]byte is not allowed: use json.RawMessage for raw JSON")
  119. case json.RawMessage:
  120. return v, nil
  121. default:
  122. b, err := json.Marshal(v)
  123. if err != nil {
  124. return nil, fmt.Errorf("marshal json: %w", err)
  125. }
  126. return json.RawMessage(b), nil
  127. }
  128. }
  129. // 构建一个请求
  130. func BuildRequest(method string, params any, id ...int) (*Request, error) {
  131. if method == "" {
  132. return nil, errors.New("method must be non-empty")
  133. }
  134. raw, err := marshalJSON(params)
  135. if err != nil {
  136. return nil, err
  137. }
  138. var rid int
  139. if len(id) > 0 {
  140. rid = id[0]
  141. } else {
  142. rid = nextID()
  143. }
  144. req := &Request{
  145. JSONRPC: "2.0",
  146. Method: method,
  147. ID: &rid,
  148. }
  149. if raw != nil { // 非空参数
  150. req.Params = raw
  151. }
  152. return req, nil
  153. }
  154. // 构建一个通知
  155. func BuildNotification(method string, params any) (*Request, error) {
  156. if method == "" {
  157. return nil, errors.New("method must be non-empty")
  158. }
  159. raw, err := marshalJSON(params)
  160. if err != nil {
  161. return nil, err
  162. }
  163. req := &Request{
  164. JSONRPC: "2.0",
  165. Method: method,
  166. }
  167. if raw != nil { // 非空参数
  168. req.Params = raw
  169. }
  170. return req, nil
  171. }
  172. // 构建成功应答
  173. func BuildResult(req *Request, result any) (*Response, error) {
  174. if req.ID == nil { // 通知类型, 不用应答
  175. return nil, nil
  176. }
  177. raw, err := marshalJSON(result)
  178. if err != nil {
  179. return nil, err
  180. }
  181. if raw == nil {
  182. raw = json.RawMessage("null")
  183. }
  184. return &Response{
  185. JSONRPC: "2.0",
  186. Result: raw,
  187. ID: req.ID,
  188. }, nil
  189. }
  190. // 构建错误应答
  191. func BuildError(req *Request, code ErrCode, message string) *Response {
  192. id := (*int)(nil)
  193. if req != nil {
  194. id = req.ID
  195. }
  196. emsg := message
  197. if emsg == "" {
  198. emsg = errMessages[code]
  199. }
  200. return &Response{
  201. JSONRPC: "2.0",
  202. Error: &Error{
  203. Code: code,
  204. Message: emsg,
  205. },
  206. ID: id,
  207. }
  208. }
  209. // 请求转字符串
  210. func (req *Request) String() (string, error) {
  211. b, err := json.Marshal(req)
  212. if err != nil {
  213. return "", fmt.Errorf("marshal request: %w", err)
  214. }
  215. return string(b), nil
  216. }
  217. // 应答转字符串
  218. func (resp *Response) String() (string, error) {
  219. b, err := json.Marshal(resp)
  220. if err != nil {
  221. return "", fmt.Errorf("marshal response: %w", err)
  222. }
  223. return string(b), nil
  224. }