-
-
Notifications
You must be signed in to change notification settings - Fork 23
/
method.go
82 lines (70 loc) · 1.69 KB
/
method.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
package jsonrpc
import (
"errors"
"sync"
)
type (
// A MethodRepository has JSON-RPC method functions.
MethodRepository struct {
m sync.RWMutex
r map[string]Metadata
}
// Metadata has method meta data.
Metadata struct {
Handler Handler
Params any
Result any
}
)
// NewMethodRepository returns new MethodRepository.
func NewMethodRepository() *MethodRepository {
return &MethodRepository{
m: sync.RWMutex{},
r: map[string]Metadata{},
}
}
// TakeMethodMetadata takes metadata in MethodRepository for request.
func (mr *MethodRepository) TakeMethodMetadata(r *Request) (Metadata, *Error) {
if r.Method == "" || r.Version != Version {
return Metadata{}, ErrInvalidParams()
}
mr.m.RLock()
md, ok := mr.r[r.Method]
mr.m.RUnlock()
if !ok {
return Metadata{}, ErrMethodNotFound()
}
return md, nil
}
// TakeMethod takes jsonrpc.Func in MethodRepository.
func (mr *MethodRepository) TakeMethod(r *Request) (Handler, *Error) { //nolint: ireturn
md, err := mr.TakeMethodMetadata(r)
if err != nil {
return nil, err
}
return md.Handler, nil
}
// RegisterMethod registers jsonrpc.Func to MethodRepository.
func (mr *MethodRepository) RegisterMethod(method string, h Handler, params, result any) error {
if method == "" || h == nil {
return errors.New("jsonrpc: method name and function should not be empty") //nolint: goerr113
}
mr.m.Lock()
mr.r[method] = Metadata{
Handler: h,
Params: params,
Result: result,
}
mr.m.Unlock()
return nil
}
// Methods returns registered methods.
func (mr *MethodRepository) Methods() map[string]Metadata {
mr.m.RLock()
ml := make(map[string]Metadata, len(mr.r))
for k, md := range mr.r {
ml[k] = md
}
mr.m.RUnlock()
return ml
}