-
Notifications
You must be signed in to change notification settings - Fork 2
/
handler.go
297 lines (248 loc) · 7.81 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
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
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
package kcd
import (
"context"
"fmt"
"net/http"
"reflect"
"runtime"
"github.com/alexisvisco/kcd/pkg/errors"
"github.com/alexisvisco/kcd/internal/cache"
"github.com/alexisvisco/kcd/internal/decoder"
)
type inputType int
const (
inputTypeResponse inputType = iota
inputTypeRequest
inputTypeInput
inputTypeCtx
)
// ErrStopHandler will stop execution of the handler, a blank response will be sent
var ErrStopHandler = errors.New("KCD_STOP_HANDLER")
// Handler returns a default http handler.
//
// The handler may use the following signature:
//
// func(
// [ctx context.Context],
// [response http.ResponseWriter],
// [request *http.Request],
// [INPUT object ptr]) ([OUTPUT object], error)
//
// INPUT and OUTPUT struct are both optional.
// As such, the minimal accepted signature is:
//
// func() error
//
//
// There is an exception because you can also use default http handler but the status code, and the render hook
// will not be used.
//
// A complete example for an INPUT struct:
// type CreateCustomerInput struct {
// Name string `path:"name"` // /some-path/{name}
// Authorization string `header:"X-authorization"` // header name 'X-authorization'
// Emails []string `query:"emails" exploder:","` // /some-path/{name}?emails=a@1.fr,b@1.fr
// Body map[string]string `json:"body"` // json body with {body: {a: "hey", b: "hoy"}}
//
// ContextualID *struct {
// ID string `ctx:"id" default:"robot"` // ctx value with key 'id' or it will default set ID to "robot"
// }
// }
//
// The wrapped handler will bind the parameters from the query-string,
// path, body and headers, context, and handle the errors.
//
// Handler will panic if the kcd handler or its input/output values
// are of incompatible type.
func Handler(h interface{}, defaultStatusCode int) http.HandlerFunc {
hv := reflect.ValueOf(h)
if hv.Kind() != reflect.Func {
panic(fmt.Sprintf("handler parameters must be a function, got %T", h))
}
ht := hv.Type()
funcName := runtime.FuncForPC(hv.Pointer()).Name()
orderInput, in := input(ht, funcName)
// check number of outputs because the std http handler don't return anything but kcd can have a func(res, req) error
// so by adding this condition we ensure this is a std http handler.
isStdHTTPHandler := isStandardHTTPHandlerInput(orderInput) && ht.NumOut() == 0
outType := output(ht, funcName, isStdHTTPHandler)
cacheStruct := cache.NewStructAnalyzer(Config.stringsTags(), Config.valuesTags(), in).Cache()
var input reflect.Value
// Wrap http handler.
httpHandler := func(w http.ResponseWriter, r *http.Request) {
// kcd handler has custom input, handle binding.
if in != nil {
inputStruct := reflect.New(in)
input = inputStruct
// Bind body
if err := Config.BindHook(w, r, input.Interface()); err != nil {
Config.ErrorHook(w, r, err, Config.LogHook)
return
}
err := decoder.NewDecoder(r, w, Config.StringsExtractors, Config.ValueExtractors).
Decode(cacheStruct, input)
if err != nil {
Config.ErrorHook(w, r, err, Config.LogHook)
return
}
if err := Config.ValidateHook(r.Context(), inputStruct.Interface()); err != nil {
Config.ErrorHook(w, r, err, Config.LogHook)
return
}
}
var (
outputStruct interface{}
err interface{}
)
err = nil
// funcIn contains the input parameters of the kcd handler call.
var args []reflect.Value
for _, t := range orderInput {
switch t {
case inputTypeInput:
args = append(args, input)
case inputTypeRequest:
args = append(args, reflect.ValueOf(r))
case inputTypeResponse:
args = append(args, reflect.ValueOf(w))
case inputTypeCtx:
args = append(args, reflect.ValueOf(r.Context()))
}
}
ret := hv.Call(args)
if !isStdHTTPHandler {
errIndex := 0
if outType != nil {
outputStruct = ret[0].Interface()
errIndex = 1
}
if !ret[errIndex].IsNil() {
err = ret[errIndex].Interface()
}
}
// the handler must stop because its a special error or std http handler
if err == ErrStopHandler || isStdHTTPHandler {
return
}
// Handle the error returned by the handler invocation, if any.
if err != nil {
Config.ErrorHook(w, r, err.(error), Config.LogHook)
return
}
// Render the response.
if err := Config.RenderHook(w, r, outputStruct, defaultStatusCode); err != nil {
Config.ErrorHook(w, r, err, Config.LogHook)
return
}
}
return httpHandler
}
var interfaceResponseWriter = reflect.TypeOf((*http.ResponseWriter)(nil)).Elem()
var interfaceCtx = reflect.TypeOf((*context.Context)(nil)).Elem()
// input checks the input parameters of a kcd handler
// and return the type of the second parameter, if any.
func input(ht reflect.Type, name string) (orderedInputType []inputType, reflectType reflect.Type) {
n := ht.NumIn()
if n > 4 {
panic(fmt.Sprintf(
"incorrect number of input parameters for handler %s, expected 0 to 4, got %d",
name, n,
))
}
orderedInputType = make([]inputType, 0)
setInputType := map[inputType]bool{}
for i := 0; i < n; i++ {
currentInput := ht.In(i)
switch {
case currentInput.Implements(interfaceResponseWriter):
if _, exist := setInputType[inputTypeResponse]; exist {
panic(fmt.Sprintf(
"invalid parameter %d at handler %s: there is already a http.ResponseWriter parameter",
i, name,
))
}
setInputType[inputTypeResponse] = true
orderedInputType = append(orderedInputType, inputTypeResponse)
case currentInput.Implements(interfaceCtx):
if _, exist := setInputType[inputTypeCtx]; exist {
panic(fmt.Sprintf(
"invalid parameter %d at handler %s: there is already a context.Context parameter",
i, name,
))
}
setInputType[inputTypeCtx] = true
orderedInputType = append(orderedInputType, inputTypeCtx)
case currentInput.ConvertibleTo(reflect.TypeOf(&http.Request{})):
if _, exist := setInputType[inputTypeRequest]; exist {
panic(fmt.Sprintf(
"invalid parameter %d at handler %s: there is already a http.Request parameter",
i, name,
))
}
setInputType[inputTypeRequest] = true
orderedInputType = append(orderedInputType, inputTypeRequest)
default:
if _, exist := setInputType[inputTypeInput]; exist {
panic(fmt.Sprintf(
"invalid parameter %d at handler %s: there is already the input parameter",
i, name,
))
}
if currentInput.Kind() != reflect.Ptr || currentInput.Elem().Kind() != reflect.Struct {
panic(fmt.Sprintf(
"invalid %d parameter for handler %s, expected pointer to struct, got %v",
n, name, currentInput,
))
}
setInputType[inputTypeInput] = true
orderedInputType = append(orderedInputType, inputTypeInput)
reflectType = currentInput.Elem()
}
}
return orderedInputType, reflectType
}
// output checks the output parameters of a kcd handler
// and return the type of the return type, if any.
func output(ht reflect.Type, name string, handler bool) reflect.Type {
n := ht.NumOut()
if n == 0 && handler {
return nil
}
if n < 1 || n > 2 {
panic(fmt.Sprintf(
"incorrect number of output parameters for handler %s, expected 1 or 2, got %d",
name, n,
))
}
// Check the type of the error parameter, which
// should always come last.
if !ht.Out(n - 1).Implements(reflect.TypeOf((*error)(nil)).Elem()) {
panic(fmt.Sprintf(
"unsupported type for handler %s output parameter: expected error interface, got %v",
name, ht.Out(n-1),
))
}
if n == 2 {
t := ht.Out(0)
if t.Kind() == reflect.Ptr {
t = t.Elem()
}
return t
}
return nil
}
func isStandardHTTPHandlerInput(orderedInputType []inputType) bool {
if len(orderedInputType) != 2 {
return false
}
isReq, isRes := false, false
for _, t := range orderedInputType {
if t == inputTypeRequest {
isReq = true
}
if t == inputTypeResponse {
isRes = true
}
}
return isRes && isReq
}