-
Notifications
You must be signed in to change notification settings - Fork 0
/
handler.go
132 lines (104 loc) · 2.29 KB
/
handler.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
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
package jsonrpc
import (
"bytes"
"io"
"net/http"
"strings"
"sync"
"github.com/lapitskyss/jsonrpc/jparser"
)
// ServeHTTP process incoming requests.
func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodPost {
w.WriteHeader(http.StatusMethodNotAllowed)
return
}
if !strings.HasPrefix(r.Header.Get("Content-Type"), s.options.ContentType) {
w.WriteHeader(http.StatusUnsupportedMediaType)
return
}
json, err := io.ReadAll(r.Body)
if err != nil {
sendInternalError(w)
return
}
if len(json) == 0 {
sendInvalidRequest(w)
return
}
if err = jparser.ValidateBytes(json); err != nil {
sendParseError(w)
return
}
if jparser.IsArray(json) {
batchLen := jparser.ArrayLength(json)
if batchLen == 0 {
sendParseError(w)
return
}
if batchLen > s.options.BatchMaxLen {
sendMaxBatchRequestsError(w)
return
}
respChan := make(chan []byte, batchLen)
var wg sync.WaitGroup
wg.Add(batchLen)
for i := 0; i < batchLen; i++ {
data := jparser.ArrayElement(json, i)
go func(data []byte) {
respChan <- s.handleRequest(r, data)
wg.Done()
}(data)
}
wg.Wait()
close(respChan)
var buffer bytes.Buffer
buffer.WriteString("[")
for resp := range respChan {
buffer.Write(resp)
buffer.WriteString(",")
}
response := buffer.Bytes()
response[len(response)-1] = ']'
send(w, response)
return
} else {
send(w, s.handleRequest(r, json))
return
}
}
// handleRequest process incoming request single time.
func (s *Server) handleRequest(r *http.Request, json []byte) []byte {
p := jparser.Parse(json)
if p.Error() != nil {
return ErrParseJSON()
}
if string(p.Version) != Version {
return responseInvalidRequest(p.ID)
}
method := p.GetMethod()
if method == "" {
return responseMethodNotFound(p.ID)
}
service := s.GetService(method)
if service == nil {
return responseMethodNotFound(p.ID)
}
f := service.handler
for i := len(service.middlewares) - 1; i >= 0; i-- {
f = service.middlewares[i](f)
}
for i := len(s.middlewares) - 1; i >= 0; i-- {
f = s.middlewares[i](f)
}
requestCtx := &RequestCtx{
R: r,
ID: p.GetId(),
Params: p.Params,
}
result, err := f(requestCtx)
if err != nil {
return responseError(p.ID, err)
}
return responseResult(p.ID, result)
}