-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathjsonrpc.go
63 lines (48 loc) · 1.16 KB
/
jsonrpc.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
package jsonrpc
import (
"errors"
"github.com/lyonnee/hmap"
"github.com/lyonnee/hvalid"
)
type Handler interface {
Handle(req *Request, resp *Response)
}
type HandlerFunc func(req *Request, resp *Response)
func (fn HandlerFunc) Handle(req *Request, resp *Response) {
fn(req, resp)
}
var handlers = hmap.New[string, Handler]()
func Register(name string, handler Handler) error {
if _, ok := handlers.LoadOrStore(name, handler); ok {
return errors.New("handler multiple registration")
}
return nil
}
func requestValidator() hvalid.ValidatorFunc[*Request] {
return hvalid.ValidatorFunc[*Request](func(req *Request) error {
if req.JSONRPC != "2.0" {
return errors.New("jsonrpc version not match")
}
return nil
})
}
func call(req *Request, resp *Response) {
resp.ID = req.ID
// 校验request合法
if err := hvalid.Validate[*Request](req, requestValidator()); err != nil {
resp.Error = InvalidRequest
return
}
defer func() {
if err := recover(); err != nil {
resp.Error = InternalError
recoverHandler(err)
}
}()
handler, ok := handlers.Load(req.Method)
if !ok {
resp.Error = MethodNotFound
return
}
handler.Handle(req, resp)
}