dispatcher.go 1.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  1. package rpc
  2. import (
  3. "io"
  4. "jrpcserver/model"
  5. )
  6. type Dispatcher struct {
  7. config interface{}
  8. serverConfig *model.ServerConfig
  9. }
  10. func NewDispatcher(config interface{}) *Dispatcher {
  11. var dispatcher Dispatcher
  12. serverConfigAccessor, ok := config.(model.ServerConfigReader)
  13. if ok {
  14. server, _ := serverConfigAccessor.ReadServerConfig()
  15. dispatcher.serverConfig = server
  16. }
  17. dispatcher.config = config
  18. return &dispatcher
  19. }
  20. func (d *Dispatcher) Execute(method string, headers map[string]string, payload io.ReadCloser) *model.RPCCommandResponse {
  21. response := model.RPCCommandResponse{}
  22. found := false
  23. for _, cmd := range d.serverConfig.Commands {
  24. if cmd.Name == method {
  25. found = true
  26. result, err := cmd.Command(d.config, headers, payload)
  27. if err.Code != 0 {
  28. response.Code = err.Code
  29. response.Error = err.Error
  30. response.RawResponse = cmd.RawResponse
  31. } else {
  32. response.Code = 0
  33. response.Value = result
  34. response.RawResponse = cmd.RawResponse
  35. }
  36. }
  37. }
  38. if !found {
  39. response.Code = 404
  40. response.Error = "command not found"
  41. }
  42. return &response
  43. }