forked from starius/api2
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.go
More file actions
221 lines (193 loc) · 6.76 KB
/
Copy pathserver.go
File metadata and controls
221 lines (193 loc) · 6.76 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
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
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
package api2
import (
"context"
"encoding/json"
"fmt"
"net/http"
"reflect"
)
type errorMessage struct {
Error string `json:"error"`
Detail json.RawMessage `json:"detail,omitempty"`
Code string `json:"code,omitempty"`
}
type Router interface {
HandleFunc(pattern string, handler func(http.ResponseWriter, *http.Request))
}
func jsonError(w http.ResponseWriter, human bool, code int, format string, args ...interface{}) error {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(code)
errmsg := fmt.Sprintf(format, args...)
return newEncoder(w, human).Encode(errorMessage{Error: errmsg})
}
// BindRoutes adds handlers of routes to http.ServeMux.
func BindRoutes(mux Router, routes []Route, opts ...Option) {
config := NewDefaultConfig()
for _, opt := range opts {
opt(config)
}
errorf := config.errorf
human := config.human
routePaths := make([]string, len(routes))
for i, route := range routes {
routePaths[i] = fmt.Sprintf("%s: %s", route.Method, route.Path)
}
// Detect route conflicts
conflicts := detectRouteConflicts(routePaths)
if len(conflicts) > 0 {
for _, conflict := range conflicts {
conflictMsg := fmt.Sprintf("Route conflict detected:\n Route %d: %s (specificity score: %d)\n Route %d: %s (specificity score: %d)\n Issue: Less specific route appears before more specific route",
conflict.route1Index, conflict.route1Path, conflict.route1Score,
conflict.route2Index, conflict.route2Path, conflict.route2Score)
panic(fmt.Sprintf("ROUTE VALIDATION FAILED: %s\n\nSuggestion: reorder routes manually with more specific routes first.", conflictMsg))
}
}
path2routes := make(map[string][]Route)
for _, route := range routes {
path := cutUrlParams(route.Path)
path2routes[path] = append(path2routes[path], route)
}
for path, routes := range path2routes {
method2routes := make(map[string][]Route, len(routes))
for _, route := range routes {
method2routes[route.Method] = append(method2routes[route.Method], route)
}
method2handler := make(map[string]http.HandlerFunc, len(routes))
for method, routes := range method2routes {
method2handler[method] = newHTTPMethodHandler(routes, human, errorf, config.middleware)
}
mux.HandleFunc(path, func(w http.ResponseWriter, r *http.Request) {
// Calling FormValue before parsing JSON "eats" r.Body if Content-Type is
// application/x-www-form-urlencoded. This happens in curl for me.
human2 := human || r.FormValue("human") != ""
if human2 {
r = r.WithContext(context.WithValue(r.Context(), humanType{}, true))
}
handler, has := method2handler[r.Method]
if !has {
if err := jsonError(w, human2, http.StatusMethodNotAllowed, "unsupported method: %v", r.Method); err != nil {
errorf("%s handler failed to send MethodNotAllowed error to client: %v", r.URL.Path, err)
}
return
}
r.Body = http.MaxBytesReader(w, r.Body, config.maxBody)
handler(w, r)
})
}
}
// GetMatcher returns a function converting http.Request to Route.
func GetMatcher(routes []Route) func(*http.Request) (*Route, bool) {
path2method2route := make(map[string]map[string]*Route)
for _, route := range routes {
route := route
method2route, has := path2method2route[route.Path]
if !has {
method2route = make(map[string]*Route)
path2method2route[route.Path] = method2route
}
method2route[route.Method] = &route
}
// Use mux to detect route.Path from http.Request.
mux := http.NewServeMux()
BindRoutes(mux, routes)
return func(r *http.Request) (*Route, bool) {
_, path := mux.Handler(r)
method2route, has := path2method2route[path]
if !has {
return nil, false
}
route, has := method2route[r.Method]
return route, has
}
}
func newHTTPMethodHandler(routes []Route, human bool, errorf func(format string, args ...interface{}), middleware Middleware) http.HandlerFunc {
if len(routes) == 1 && len(findUrlKeys(routes[0].Path)) == 0 {
// Single handler without URL parameters.
return newHTTPHandler(routes[0], human, errorf, middleware)
}
paths := make([]string, 0, len(routes))
handlers := make([]http.HandlerFunc, 0, len(routes))
for _, route := range routes {
paths = append(paths, route.Path)
handlers = append(handlers, newHTTPHandler(route, human, errorf, middleware))
}
c := newPathClassifier(paths)
return func(w http.ResponseWriter, r *http.Request) {
index, param2value := c.Classify(r.URL.Path)
if index == -1 {
// Calling FormValue before parsing JSON "eats" r.Body if Content-Type is
// application/x-www-form-urlencoded. This happens in curl for me.
human2 := human || r.FormValue("human") != ""
if err := jsonError(w, human2, http.StatusNotFound, "failed to find route by path"); err != nil {
errorf("%s handler failed to send NotFound error to client: %v", r.URL.Path, err)
}
return
}
handler := handlers[index]
r = r.WithContext(context.WithValue(r.Context(), paramMapType{}, param2value))
handler(w, r)
}
}
func newHTTPHandler(route Route, human bool, errorf func(format string, args ...interface{}), middleware Middleware) http.HandlerFunc {
h := route.Handler
t := route.Transport
if t == nil {
t = DefaultTransport
}
if m, ok := h.(*interfaceMethod); ok {
h = m.Func()
}
handlerValue := reflect.ValueOf(h)
handlerType := handlerValue.Type()
validateHandler(handlerType, route.Path)
return func(w http.ResponseWriter, r *http.Request) {
ctx := r.Context()
req := reflect.New(handlerType.In(1).Elem()).Interface()
ctx, err := t.DecodeRequest(ctx, r, req)
if err != nil {
err = t.EncodeError(ctx, w, httpError{
Code: http.StatusBadRequest,
Message: fmt.Sprintf("failed to parse request: %v", err),
})
if err != nil {
errorf("%s %s handler failed to send parsing error to client: %v", r.Method, r.URL.Path, err)
}
return
}
start := func(ctx context.Context, req any) (any, any) {
results := handlerValue.Call([]reflect.Value{reflect.ValueOf(ctx), reflect.ValueOf(req)})
resp := results[0].Interface()
errReflect := results[1].Interface()
return resp, errReflect
}
var resp any
var errReflect any
switch middleware != nil {
case true:
resp, errReflect = middleware(ctx, req, start)
default:
resp, errReflect = start(ctx, req)
}
if errReflect != nil {
errorf("%s %s handler failed: %v", r.Method, r.URL.Path, errReflect)
if err := t.EncodeError(ctx, w, errReflect.(error)); err != nil {
errorf("%s %s handler failed to send handler error to client: %v", r.Method, r.URL.Path, err)
}
return
}
if err := t.EncodeResponse(ctx, w, resp); err != nil {
errorf("%s %s handler failed to write response: %v", r.Method, r.URL.Path, err)
return
}
}
}
type httpError struct {
Code int
Message string
}
func (e httpError) HttpCode() int {
return e.Code
}
func (e httpError) Error() string {
return e.Message
}