jsonrpc_router.go 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. package jsonrpclite
  2. import (
  3. "errors"
  4. "fmt"
  5. "reflect"
  6. )
  7. type rpcRouter struct {
  8. services map[string]*rpcService //Services in router
  9. }
  10. // NewRpcRouter Create a new rpc router.
  11. func NewRpcRouter() *rpcRouter {
  12. return new(rpcRouter)
  13. }
  14. // dispatchRequests Dispatch request/s to services and get the response/s
  15. func (router *rpcRouter) dispatchRequests(serviceName string, requests []rpcRequest) []rpcResponse {
  16. defer func() {
  17. var p = any(recover())
  18. if p != nil {
  19. errStr := fmt.Sprintln("Internal JSON-RPC error.") + fmt.Sprintf("%v", p)
  20. err := newRpcError(-32603, errStr)
  21. response := rpcResponse{-1, true, err}
  22. var responseErr any = newRpcResponseError(response)
  23. panic(responseErr)
  24. }
  25. }()
  26. rpcService := router.getService(serviceName)
  27. if rpcService == nil {
  28. var err any = errors.New("Service " + serviceName + " does not exist.")
  29. panic(err)
  30. } else {
  31. if len(requests) > 1 {
  32. var responses = make([]rpcResponse, 0)
  33. for i := 0; i < len(requests); i++ {
  34. request := requests[i]
  35. response := rpcService.invoke(request)
  36. if !request.isNotification() {
  37. responses = append(responses, rpcResponse{request.id, false, response.result})
  38. }
  39. }
  40. return responses
  41. } else {
  42. var responses = make([]rpcResponse, 0)
  43. request := requests[0]
  44. response := rpcService.invoke(request)
  45. if !request.isNotification() {
  46. responses = append(responses, response)
  47. }
  48. return responses
  49. }
  50. }
  51. }
  52. //Get the service by service name
  53. func (router *rpcRouter) getService(serviceName string) *rpcService {
  54. if router.services == nil {
  55. return nil
  56. }
  57. return router.services[serviceName]
  58. }
  59. // RegisterService Register the logic service into the router
  60. func (router *rpcRouter) RegisterService(serviceName string, serviceInstance any) {
  61. instanceType := reflect.TypeOf(serviceInstance)
  62. s := newRpcService(serviceName, serviceInstance)
  63. numMethod := instanceType.NumMethod()
  64. if numMethod > 0 {
  65. for i := 0; i < numMethod; i++ {
  66. method := instanceType.Method(i)
  67. if method.IsExported() {
  68. instanceMethod, ok := instanceType.MethodByName(method.Name)
  69. if ok {
  70. rpcMethod := newRpcMethod(instanceMethod)
  71. s.addMethod(rpcMethod)
  72. } else {
  73. var err any = errors.New("The output param count of" + instanceType.Name() + "." + instanceMethod.Name + " is not matched")
  74. panic(err)
  75. }
  76. }
  77. }
  78. }
  79. if router.services == nil {
  80. router.services = make(map[string]*rpcService)
  81. }
  82. router.services[serviceName] = s
  83. }