jsonrpc_method.go 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. package jsonrpclite
  2. import (
  3. "errors"
  4. "reflect"
  5. )
  6. type rpcMethodType uint32
  7. const (
  8. returnMethod rpcMethodType = iota //Handler with return value
  9. voidMethod //Handler without return value
  10. )
  11. type rpcMethodHandler func(params []any) any
  12. type rpcMethod struct {
  13. handler rpcMethodHandler //The method reflect value
  14. name string //The name of the method
  15. methodType rpcMethodType //The type of the handler
  16. paramTypes []reflect.Type //The types of the handler params
  17. returnType reflect.Type //The type of return value
  18. }
  19. //call the method of the rpcMethod
  20. func (method *rpcMethod) call(params []any) any {
  21. return method.handler(params)
  22. }
  23. // newRpcMethod Create a new rpcMethod instance
  24. func newRpcMethod(serviceMethod reflect.Method) *rpcMethod {
  25. //Parse out
  26. outNum := serviceMethod.Type.NumOut()
  27. if outNum > 1 {
  28. var err any = errors.New("The return value count of method " + serviceMethod.Name + " should be 0 or 1")
  29. panic(err)
  30. }
  31. //Parse in
  32. inNum := serviceMethod.Type.NumIn()
  33. paramTypes := make([]reflect.Type, inNum)
  34. for i := 0; i < inNum; i++ {
  35. paramTypes[i] = serviceMethod.Type.In(i)
  36. }
  37. method := new(rpcMethod)
  38. method.name = serviceMethod.Name
  39. method.paramTypes = paramTypes
  40. if outNum == 0 {
  41. method.methodType = voidMethod
  42. method.returnType = reflect.TypeOf(nil)
  43. method.handler = func(params []any) any {
  44. paramCount := len(params)
  45. callParams := make([]reflect.Value, paramCount)
  46. for i := 0; i < paramCount; i++ {
  47. callParams[i] = reflect.ValueOf(params[i])
  48. }
  49. serviceMethod.Func.Call(callParams)
  50. return nil
  51. }
  52. } else {
  53. method.methodType = returnMethod
  54. method.returnType = serviceMethod.Type.Out(0)
  55. method.handler = func(params []any) any {
  56. paramCount := len(params)
  57. callParams := make([]reflect.Value, paramCount)
  58. for i := 0; i < paramCount; i++ {
  59. callParams[i] = reflect.ValueOf(params[i])
  60. }
  61. result := serviceMethod.Func.Call(callParams)[0]
  62. return result.Interface()
  63. }
  64. }
  65. return method
  66. }