You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

70 lines
1.4 KiB

  1. package jsonrpc
  2. import (
  3. "errors"
  4. "sync"
  5. )
  6. type (
  7. // A MethodRepository has JSON-RPC method functions.
  8. MethodRepository struct {
  9. m sync.RWMutex
  10. r map[string]Metadata
  11. }
  12. // Metadata has method meta data.
  13. Metadata struct {
  14. Handler Handler
  15. Params interface{}
  16. Result interface{}
  17. }
  18. )
  19. // NewMethodRepository returns new MethodRepository.
  20. func NewMethodRepository() *MethodRepository {
  21. return &MethodRepository{
  22. m: sync.RWMutex{},
  23. r: map[string]Metadata{},
  24. }
  25. }
  26. // TakeMethod takes jsonrpc.Func in MethodRepository.
  27. func (mr *MethodRepository) TakeMethod(r *Request) (Handler, *Error) {
  28. if r.Method == "" || r.Version != Version {
  29. return nil, ErrInvalidParams()
  30. }
  31. mr.m.RLock()
  32. md, ok := mr.r[r.Method]
  33. mr.m.RUnlock()
  34. if !ok {
  35. return nil, ErrMethodNotFound()
  36. }
  37. return md.Handler, nil
  38. }
  39. // RegisterMethod registers jsonrpc.Func to MethodRepository.
  40. func (mr *MethodRepository) RegisterMethod(method string, h Handler, params, result interface{}) error {
  41. if method == "" || h == nil {
  42. return errors.New("jsonrpc: method name and function should not be empty")
  43. }
  44. mr.m.Lock()
  45. mr.r[method] = Metadata{
  46. Handler: h,
  47. Params: params,
  48. Result: result,
  49. }
  50. mr.m.Unlock()
  51. return nil
  52. }
  53. // Methods returns registered methods.
  54. func (mr *MethodRepository) Methods() map[string]Metadata {
  55. mr.m.RLock()
  56. ml := make(map[string]Metadata, len(mr.r))
  57. for k, md := range mr.r {
  58. ml[k] = md
  59. }
  60. mr.m.RUnlock()
  61. return ml
  62. }