1
package jsonrpc
2

3
import (
4
	"errors"
5
	"sync"
6
)
7

8
type (
9
	// A MethodRepository has JSON-RPC method functions.
10
	MethodRepository struct {
11
		m sync.RWMutex
12
		r map[string]Metadata
13
	}
14
	// Metadata has method meta data.
15
	Metadata struct {
16
		Handler Handler
17
		Params  interface{}
18
		Result  interface{}
19
	}
20
)
21

22
// NewMethodRepository returns new MethodRepository.
23
func NewMethodRepository() *MethodRepository {
24 6
	return &MethodRepository{
25 6
		m: sync.RWMutex{},
26 6
		r: map[string]Metadata{},
27
	}
28
}
29

30
// TakeMethodMetadata takes metadata in MethodRepository for request.
31
func (mr *MethodRepository) TakeMethodMetadata(r *Request) (Metadata, *Error) {
32

33 6
	if r.Method == "" || r.Version != Version {
34 6
		return Metadata{}, ErrInvalidParams()
35
	}
36

37 6
	mr.m.RLock()
38 6
	md, ok := mr.r[r.Method]
39 6
	mr.m.RUnlock()
40 6
	if !ok {
41 6
		return Metadata{}, ErrMethodNotFound()
42
	}
43

44 6
	return md, nil
45
}
46

47
// TakeMethod takes jsonrpc.Func in MethodRepository.
48
func (mr *MethodRepository) TakeMethod(r *Request) (Handler, *Error) {
49 6
	md, err := mr.TakeMethodMetadata(r)
50 6
	if err != nil {
51 6
		return nil, err
52
	}
53 6
	return md.Handler, nil
54
}
55

56
// RegisterMethod registers jsonrpc.Func to MethodRepository.
57
func (mr *MethodRepository) RegisterMethod(method string, h Handler, params, result interface{}) error {
58 6
	if method == "" || h == nil {
59 6
		return errors.New("jsonrpc: method name and function should not be empty")
60
	}
61 6
	mr.m.Lock()
62 6
	mr.r[method] = Metadata{
63 6
		Handler: h,
64 6
		Params:  params,
65 6
		Result:  result,
66
	}
67 6
	mr.m.Unlock()
68 6
	return nil
69
}
70

71
// Methods returns registered methods.
72
func (mr *MethodRepository) Methods() map[string]Metadata {
73 6
	mr.m.RLock()
74 6
	ml := make(map[string]Metadata, len(mr.r))
75
	for k, md := range mr.r {
76 6
		ml[k] = md
77
	}
78 6
	mr.m.RUnlock()
79 6
	return ml
80
}

Read our documentation on viewing source code .

Loading