-
Notifications
You must be signed in to change notification settings - Fork 0
/
manager2.go
71 lines (58 loc) · 1.61 KB
/
manager2.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
package jsonrpc2
import (
"encoding/json"
"reflect"
"github.com/ivanovuri/jsonrpc2/inspect"
)
type Manager struct {
methods calls
}
func (m *Manager) RegisterMethod(name string, method any) error {
return m.methods.Add(name, method)
}
func (m *Manager) DeregisterMethod(name string, method any) error {
return m.methods.Remove(name)
}
func (m *Manager) ProcessRequest(request Request) *Response {
if callableMethod, rpcErr := m.methods.Get(request.Method); rpcErr != nil {
return ErrorReply(request.Id,
MethodNotFoundCode.Code(),
MethodNotFoundCode.Message())
} else {
var in []reflect.Value
var err error
if inspect.NamedCall(callableMethod) {
in, err = inspect.ParseNamedParams(request.Params, callableMethod)
if err != nil {
return ErrorReply(request.Id,
InvalidParamsCode.Code(),
InvalidParamsCode.Message())
}
} else {
in, err = inspect.ParsePositionalParams(request.Params, callableMethod)
if err != nil {
return ErrorReply(request.Id,
InvalidParamsCode.Code(),
InvalidParamsCode.Message())
}
}
result := inspect.ExecuteMethod(callableMethod, in)
replyObj := MakeReply(request, result)
return replyObj
}
}
func (m *Manager) ProcessSingleRequest(singleRequest Request) []byte {
result, _ := json.Marshal(m.ProcessRequest(singleRequest))
return result
}
func (m *Manager) ProcessBatchRequest(batch []Request) []byte {
var replies []Response
for _, singleRequest := range batch {
processed := m.ProcessRequest(singleRequest)
if processed != nil {
replies = append(replies, *processed)
}
}
result, _ := json.Marshal(replies)
return result
}