-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathhandler.go
More file actions
76 lines (61 loc) · 1.73 KB
/
handler.go
File metadata and controls
76 lines (61 loc) · 1.73 KB
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
package jsonrpc
import (
"net/http"
)
// Handler represents jsonrpc handler.
//
// if your handler return any error, and you don`t use SetInvalidRequestParamsError()
// response will have code -32603 and message "Internal error"
//
// if you use SetInvalidRequestParamsError() response will have code -32602 and message "Invalid params"
type Handler func(w ResponseWriter, r *Request) error
type httpHandler struct {
routes map[string]Handler
}
// ServeHTTP provides basic JSON-RPC handling.
func (h *httpHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
if err := h.serveHTTPReq(w, r); err != nil {
w.WriteHeader(http.StatusInternalServerError)
}
}
func (h *httpHandler) serveHTTPReq(w http.ResponseWriter, r *http.Request) error {
requests, err := parseRequest(r)
if err != nil {
return sendResponse(w, []*response{newErrorResponse(err)})
}
responses := make([]*response, 0)
for _, request := range requests {
if resp := h.HandleMethod(request); request.ID != nil {
responses = append(responses, resp)
}
}
return sendResponse(w, responses)
}
// HandleMethod handle JSON-RPC method.
func (h *httpHandler) HandleMethod(r *Request) *response {
res := newResponse(r)
handler, err := h.GetMethod(r)
if err != nil {
res.Error = err
return res
}
if handlerErr := handler(res, r); handlerErr != nil && res.Error == nil {
if r.parsingError {
res.Error = errParse()
} else {
res.Error = errInternal()
}
}
return res
}
// GetMethod returns method handler.
func (h *httpHandler) GetMethod(r *Request) (Handler, *respError) {
if r.Method == "" || r.Version != Version {
return nil, errInvalidRequest()
}
handler, ok := h.routes[r.Method]
if !ok {
return nil, errMethodNotFound()
}
return handler, nil
}