jsonrpc_utils.go 5.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199
  1. package jsonrpclite
  2. import (
  3. "encoding/json"
  4. "fmt"
  5. "reflect"
  6. )
  7. type requestData struct {
  8. JsonRpc string `json:"jsonrpc"`
  9. Id any `json:"id"`
  10. Method string `json:"method"`
  11. Params json.RawMessage `json:"params"`
  12. }
  13. func decodeRequest(service *rpcService, data requestData) rpcRequest {
  14. defer func() {
  15. var p = any(recover())
  16. if p != nil {
  17. responseErr, ok := p.(*RpcResponseError)
  18. if ok {
  19. panic(any(responseErr))
  20. } else {
  21. errStr := fmt.Sprintln("The JSON sent is not a valid Request object.") + fmt.Sprintf("%v", p)
  22. err := newRpcError(-32600, errStr)
  23. response := rpcResponse{-1, true, err}
  24. var responseErr any = newRpcResponseError(response)
  25. panic(responseErr)
  26. }
  27. }
  28. }()
  29. method := service.methods[data.Method]
  30. if method == nil {
  31. errStr := "The method does not exist / is not available."
  32. err := newRpcError(-32601, errStr)
  33. response := rpcResponse{-1, true, err}
  34. var responseErr any = newRpcResponseError(response)
  35. panic(responseErr)
  36. }
  37. request := rpcRequest{id: data.Id, method: data.Method}
  38. paramTypes := method.paramTypes
  39. paramCount := len(paramTypes)
  40. switch paramCount {
  41. case 0:
  42. errStr := fmt.Sprintln("Invalid method parameter(s).") + "method " + data.Method + "'s param count should contains receiver."
  43. err := newRpcError(-32601, errStr)
  44. response := rpcResponse{-1, true, err}
  45. var responseErr any = newRpcResponseError(response)
  46. panic(responseErr)
  47. case 1:
  48. if data.Params != nil {
  49. errStr := fmt.Sprintln("Invalid method parameter(s).") + "method " + data.Method + "'s param count should be 0."
  50. err := newRpcError(-32601, errStr)
  51. response := rpcResponse{-1, true, err}
  52. var responseErr any = newRpcResponseError(response)
  53. panic(responseErr)
  54. }
  55. request.params = make([]rpcParam, 0)
  56. case 2:
  57. if data.Params == nil {
  58. errStr := fmt.Sprintln("Invalid method parameter(s).") + "Param of method " + data.Method + "is empty."
  59. err := newRpcError(-32601, errStr)
  60. response := rpcResponse{-1, true, err}
  61. var responseErr any = newRpcResponseError(response)
  62. panic(responseErr)
  63. }
  64. paramStr := string(data.Params)
  65. isArray := len(paramStr) > 0 && paramStr[0] == '['
  66. if isArray {
  67. //Array is not matched
  68. errStr := fmt.Sprintln("Invalid method parameter(s).") + "Param count of method" + data.Method + " is not matched."
  69. err := newRpcError(-32601, errStr)
  70. response := rpcResponse{-1, true, err}
  71. var responseErr any = newRpcResponseError(response)
  72. panic(responseErr)
  73. } else {
  74. rpcParamValue := reflect.New(method.paramTypes[1]).Elem().Interface()
  75. err := json.Unmarshal(data.Params, &rpcParamValue)
  76. if err == nil {
  77. rpcParamValue = reflect.ValueOf(rpcParamValue).Convert(method.paramTypes[1]).Interface()
  78. request.params = []rpcParam{{method.paramTypes[1], rpcParamValue}}
  79. } else {
  80. errStr := fmt.Sprintln("Invalid method parameter(s).") + "UnMarshal param error:" + err.Error()
  81. err := newRpcError(-32601, errStr)
  82. response := rpcResponse{-1, true, err}
  83. var responseErr any = newRpcResponseError(response)
  84. panic(responseErr)
  85. }
  86. }
  87. default:
  88. //Array
  89. paramValues := make([]any, paramCount-1)
  90. for i := 0; i < paramCount-1; i++ {
  91. paramType := paramTypes[i+1]
  92. paramValue := reflect.New(paramType).Interface()
  93. paramValues[i] = paramValue
  94. }
  95. err := json.Unmarshal(data.Params, &paramValues)
  96. if err == nil {
  97. rpcParams := make([]rpcParam, paramCount-1)
  98. for i := 0; i < paramCount-1; i++ {
  99. rpcParams[i] = rpcParam{method.paramTypes[i+1], reflect.ValueOf(paramValues[i]).Elem().Interface()}
  100. }
  101. request.params = rpcParams
  102. } else {
  103. errStr := fmt.Sprintln("Invalid method parameter(s).") + "UnMarshal param error:" + err.Error()
  104. err := newRpcError(-32601, errStr)
  105. response := rpcResponse{-1, true, err}
  106. var responseErr any = newRpcResponseError(response)
  107. panic(responseErr)
  108. }
  109. }
  110. return request
  111. }
  112. func decodeRequestString(service *rpcService, jsonStr string) []rpcRequest {
  113. defer func() {
  114. var p = any(recover())
  115. if p != nil {
  116. responseErr, ok := p.(*RpcResponseError)
  117. if ok {
  118. panic(any(responseErr))
  119. } else {
  120. errStr := fmt.Sprintln("Invalid JSON was received by the server. An error occurred on the server while parsing the JSON text.") + fmt.Sprintf("%v", p)
  121. err := newRpcError(-32700, errStr)
  122. response := rpcResponse{-1, true, err}
  123. var responseErr any = newRpcResponseError(response)
  124. panic(responseErr)
  125. }
  126. }
  127. }()
  128. isArray := len(jsonStr) > 0 && jsonStr[0] == '['
  129. if isArray {
  130. var requestsData []requestData
  131. err := json.Unmarshal([]byte(jsonStr), &requestsData)
  132. if err == nil {
  133. requests := make([]rpcRequest, len(requestsData))
  134. for i := 0; i < len(requestsData); i++ {
  135. requests[i] = decodeRequest(service, requestsData[i])
  136. }
  137. return requests
  138. } else {
  139. panic(any(err))
  140. }
  141. } else {
  142. var requestData = new(requestData)
  143. err := json.Unmarshal([]byte(jsonStr), &requestData)
  144. if err == nil {
  145. request := decodeRequest(service, *requestData)
  146. return []rpcRequest{request}
  147. } else {
  148. panic(any(err))
  149. }
  150. }
  151. return nil
  152. }
  153. func createResponseData(response rpcResponse) map[string]any {
  154. result := make(map[string]any)
  155. result["jsonrpc"] = "2.0"
  156. result["id"] = response.id
  157. if response.isError {
  158. result["error"] = response.result
  159. } else {
  160. result["result"] = response.result
  161. }
  162. return result
  163. }
  164. func encodeResponses(responses []rpcResponse) []byte {
  165. if len(responses) == 0 {
  166. return nil
  167. }
  168. if len(responses) == 1 {
  169. response := responses[0]
  170. result := createResponseData(response)
  171. buffer, err := json.Marshal(result)
  172. if err == nil {
  173. return buffer
  174. }
  175. var jsonError any = err
  176. panic(jsonError)
  177. } else {
  178. numResponses := len(responses)
  179. results := make([]map[string]any, numResponses)
  180. for i := 0; i < numResponses; i++ {
  181. response := responses[i]
  182. result := createResponseData(response)
  183. results[i] = result
  184. }
  185. buffer, err := json.Marshal(results)
  186. if err == nil {
  187. return buffer
  188. }
  189. var jsonError any = err
  190. panic(jsonError)
  191. }
  192. }