jsonrpc_service.go 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  1. package jsonrpclite
  2. import "errors"
  3. type rpcService struct {
  4. name string //The name of the service
  5. instance any //The real instance of the service
  6. methods map[string]*rpcMethod //Methods belong to this service
  7. }
  8. // addMethod Add method into the service
  9. func (service *rpcService) addMethod(method *rpcMethod) {
  10. if service.methods == nil {
  11. service.methods = make(map[string]*rpcMethod)
  12. }
  13. service.methods[method.name] = method
  14. }
  15. // invoke call method of service by method name and parameter.
  16. func (service *rpcService) invoke(request rpcRequest) rpcResponse {
  17. if service.methods == nil {
  18. var err any = errors.New("Can not find method " + request.method)
  19. panic(err)
  20. }
  21. paramCount := len(request.params)
  22. callParams := make([]any, paramCount+1)
  23. callParams[0] = service.instance
  24. for i := 0; i < paramCount; i++ {
  25. callParams[i+1] = request.params[i].value
  26. }
  27. method := service.methods[request.method]
  28. result := method.call(callParams)
  29. response := rpcResponse{id: request.id, isError: false, result: result}
  30. return response
  31. }
  32. // newRpcService Create a new rpcService
  33. func newRpcService(name string, instance any) *rpcService {
  34. service := new(rpcService)
  35. service.instance = instance
  36. service.methods = make(map[string]*rpcMethod)
  37. service.name = name
  38. return service
  39. }