-
Notifications
You must be signed in to change notification settings - Fork 33
/
handlers.go
113 lines (93 loc) · 3.06 KB
/
handlers.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
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
// jsonrpc contains the common JSON RPC structures Infura products use.
package jsonrpc
import (
"context"
"encoding/json"
"io/ioutil"
"net/http"
)
// RequestHandlerFunc is a helper for handling JSONRPC Requests over HTTP
// It can be used by microservices to handle JSONRPC methods. For example:
//
// http.Handle("/", RequestHandlerFunc(func(ctx context.Context, r *Request) (interface{}, *Error) {
// if r.Method != "eth_blockNumber" {
// return nil, MethodNotSupported(fmt.Sprintf("unsupported method %s", r.Method))
// }
//
// return "0x123456", nil
// }))
func RequestHandlerFunc(fn requestHandlerFunc) *requestHandlerFunc {
return &fn
}
type RequestContext struct {
context.Context
}
func (rc *RequestContext) HTTPRequest() *http.Request {
return rc.Value(contextKeyHTTPRequest).(*http.Request)
}
func (rc *RequestContext) HTTPResponseWriter() http.ResponseWriter {
return rc.Value(contextKeyHTTPResponseWriter).(http.ResponseWriter)
}
func (rc *RequestContext) RawJSON() json.RawMessage {
return rc.Value(contextKeyRawJSON).(json.RawMessage)
}
type contextKey string
func (c contextKey) String() string {
return "jsonrpc context key " + string(c)
}
var (
contextKeyHTTPRequest = contextKey("HTTP Request")
contextKeyHTTPResponseWriter = contextKey("HTTP Response Writer")
contextKeyRawJSON = contextKey("Raw JSON")
)
type requestHandlerFunc func(ctx RequestContext, request *Request) (interface{}, *Error)
func (h requestHandlerFunc) ServeHTTP(w http.ResponseWriter, r *http.Request) {
buff, err := ioutil.ReadAll(r.Body)
if err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
if r.Header.Get("Content-Type") != "application/json" {
http.Error(w, "invalid content type, only application/json is supported", http.StatusUnsupportedMediaType)
return
}
request := Request{}
err = json.Unmarshal(buff, &request)
if err != nil {
// return a generic jsonrpc response
WriteResponse(w, nil, nil, InvalidRequest(err.Error()))
return
}
ctx := context.WithValue(r.Context(), contextKeyHTTPRequest, r)
ctx = context.WithValue(ctx, contextKeyRawJSON, json.RawMessage(buff))
ctx = context.WithValue(ctx, contextKeyHTTPResponseWriter, w)
result, e := h(RequestContext{ctx}, &request)
WriteResponse(w, &request, result, e)
}
func WriteResponse(w http.ResponseWriter, request *Request, result interface{}, e *Error) {
response := struct {
JSONRPC string `json:"jsonrpc"`
ID *ID `json:"id,omitempty"`
Result interface{} `json:"result,omitempty"`
Error interface{} `json:"error,omitempty"`
}{
JSONRPC: "2.0",
}
if request != nil {
response.ID = &request.ID
}
response.Result = result
if e != nil {
// NOTE: setting `response.Error = e` if e is nil causes `"error": null` to be included
// in the Response. See https://play.golang.org/p/Oe3MFR3wwAu
response.Error = e
}
b, err := json.Marshal(&response)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusOK)
_, _ = w.Write(b)
}