forked from go-aah/aah
-
Notifications
You must be signed in to change notification settings - Fork 0
/
bind.go
325 lines (280 loc) · 10.2 KB
/
bind.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
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
// Copyright (c) Jeevanandam M. (https://github.com/jeevatkm)
// go-aah/aah source code and usage is governed by a MIT style
// license that can be found in the LICENSE file.
package aah
import (
"errors"
"fmt"
"net/http"
"net/url"
"reflect"
"strings"
"aahframework.org/ahttp.v0"
"aahframework.org/essentials.v0"
"aahframework.org/valpar.v0"
)
const (
// KeyViewArgRequestParams key name is used to store HTTP Request Params instance
// into `ViewArgs`.
KeyViewArgRequestParams = "_aahRequestParams"
keyOverrideI18nName = "lang"
allContentTypes = "*/*"
)
var (
keyQueryParamName = keyOverrideI18nName
keyPathParamName = keyOverrideI18nName
requestParsers = make(map[string]requestParser)
isContentNegotiationEnabled bool
acceptedContentTypes []string
offeredContentTypes []string
autobindPriority []string
errInvalidParsedValue = errors.New("aah: parsed value is invalid")
)
type requestParser func(ctx *Context) flowResult
//‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾
// Package method
//___________________________________
// AddValueParser method adds given custom value parser for the `reflect.Type`
func AddValueParser(typ reflect.Type, parser valpar.Parser) error {
return valpar.AddValueParser(typ, parser)
}
//‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾
// Bind Middleware
//___________________________________
// BindMiddleware method parses the incoming HTTP request to collects request
// parameters (Path, Form, Query, Multipart) stores into context. Request
// params are made available in View via template functions.
func BindMiddleware(ctx *Context, m *Middleware) {
if AppI18n() != nil {
// i18n locale HTTP header `Accept-Language` value override via
// Path Variable and URL Query Param (config i18n { param_name { ... } }).
// Note: Query parameter takes precedence of all.
if locale := firstNonZeroString(
ctx.Req.QueryValue(keyQueryParamName),
ctx.Req.PathValue(keyPathParamName)); !ess.IsStrEmpty(locale) {
ctx.Req.Locale = ahttp.NewLocale(locale)
}
}
if ctx.Req.Method == ahttp.MethodGet {
goto PCont
}
ctx.Log().Debugf("Request Content-Type mime: %s", ctx.Req.ContentType.Mime)
// Content Negotitaion - Accepted & Offered, refer to GitHub #75
if isContentNegotiationEnabled {
if len(acceptedContentTypes) > 0 &&
!ess.IsSliceContainsString(acceptedContentTypes, ctx.Req.ContentType.Mime) {
ctx.Log().Warnf("Content type '%v' not accepted by server", ctx.Req.ContentType.Mime)
ctx.Reply().Error(&Error{
Reason: ErrContentTypeNotAccepted,
Code: http.StatusUnsupportedMediaType,
Message: http.StatusText(http.StatusUnsupportedMediaType),
})
return
}
if len(offeredContentTypes) > 0 &&
!ess.IsSliceContainsString(offeredContentTypes, ctx.Req.AcceptContentType.Mime) {
ctx.Reply().Error(&Error{
Reason: ErrContentTypeNotOffered,
Code: http.StatusNotAcceptable,
Message: http.StatusText(http.StatusNotAcceptable),
})
ctx.Log().Warnf("Content type '%v' not offered by server", ctx.Req.AcceptContentType.Mime)
return
}
}
// Prevent DDoS attacks by large HTTP request bodies by enforcing
// configured hard limit, GitHub #83.
if ctx.Req.ContentType.Mime != ahttp.ContentTypeMultipartForm.Mime {
ctx.Req.Unwrap().Body = http.MaxBytesReader(ctx.Res, ctx.Req.Unwrap().Body,
firstNonZeroInt64(ctx.route.MaxBodySize, appMaxBodyBytesSize))
}
// Parse request content by Content-Type
if parser, found := requestParsers[ctx.Req.ContentType.Mime]; found {
if res := parser(ctx); res == flowStop {
return
}
}
PCont:
// Compose request details, we can log at the end of the request.
if isDumpLogEnabled {
ctx.Set(keyAahRequestDump, composeRequestDump(ctx))
}
m.Next(ctx)
}
//‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾
// Content Parser methods
//___________________________________
func multipartFormParser(ctx *Context) flowResult {
if err := ctx.Req.Unwrap().ParseMultipartForm(appMultipartMaxMemory); err != nil {
ctx.Log().Errorf("Unable to parse multipart form: %s", err)
} else {
ctx.Req.Params.Form = ctx.Req.Unwrap().MultipartForm.Value
ctx.Req.Params.File = ctx.Req.Unwrap().MultipartForm.File
}
return flowCont
}
func formParser(ctx *Context) flowResult {
if err := ctx.Req.Unwrap().ParseForm(); err != nil {
ctx.Log().Errorf("Unable to parse form: %s", err)
} else {
ctx.Req.Params.Form = ctx.Req.Unwrap().Form
}
return flowCont
}
//‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾
// Action Parameters Auto Parse
//___________________________________
func parseParameters(ctx *Context) ([]reflect.Value, *Error) {
paramCnt := len(ctx.action.Parameters)
// If parameters not exists, return here
if paramCnt == 0 {
return emptyArg, nil
}
// Parse and Bind parameters
params := createParams(ctx)
var err error
actionArgs := make([]reflect.Value, paramCnt)
for idx, val := range ctx.action.Parameters {
var result reflect.Value
if vpFn, found := valpar.ValueParser(val.Type); found {
result, err = vpFn(val.Name, val.Type, params)
// GitHub #132 Validation implementation
if rule, found := ctx.route.ValidationRule(val.Name); found {
if !valpar.ValidateValue(result.Interface(), rule) {
errMsg := fmt.Sprintf("Path param validation failed [name: %s, rule: %s, value: %v]",
val.Name, rule, result.Interface())
ctx.Log().Error(errMsg)
return nil, &Error{
Reason: ErrValidation,
Code: http.StatusBadRequest,
Message: http.StatusText(http.StatusBadRequest),
Data: errMsg,
}
}
}
} else if val.kind == reflect.Struct {
ct := ctx.Req.ContentType.Mime
if ct == ahttp.ContentTypeJSON.Mime || ct == ahttp.ContentTypeJSONText.Mime ||
ct == ahttp.ContentTypeXML.Mime || ct == ahttp.ContentTypeXMLText.Mime {
result, err = valpar.Body(ct, ctx.Req.Body(), val.Type)
if isDumpLogEnabled && dumpRequestBody {
addReqBodyIntoCtx(ctx, result)
}
} else {
result, err = valpar.Struct("", val.Type, params)
}
}
// check error
if err != nil {
if !result.IsValid() {
ctx.Log().Errorf("Parsed result value is invalid or value parser not found [param: %s, type: %s]",
val.Name, val.Type)
}
return nil, &Error{
Reason: ErrInvalidRequestParameter,
Code: http.StatusBadRequest,
Message: http.StatusText(http.StatusBadRequest),
Data: err,
}
}
// Apply Validation for type `struct`
if val.kind == reflect.Struct {
if errs, _ := valpar.Validate(result.Interface()); errs != nil {
ctx.Log().Errorf("Param validation failed [name: %s, type: %s], Validation Errors:\n%v",
val.Name, val.Type, errs.Error())
return nil, &Error{
Reason: ErrValidation,
Code: http.StatusBadRequest,
Message: http.StatusText(http.StatusBadRequest),
Data: errs,
}
}
}
// set action parameter value
actionArgs[idx] = result
}
return actionArgs, nil
}
// Create param values based on autobind priority
func createParams(ctx *Context) url.Values {
params := make(url.Values)
for _, priority := range autobindPriority {
switch priority {
case "P": // Path Values
for k, v := range ctx.Req.Params.Path {
params.Set(k, v)
}
case "F": // Form Values
for k, v := range ctx.Req.Params.Form {
params[k] = v
}
case "Q": // Query Values
for k, v := range ctx.Req.Params.Query {
params[k] = v
}
}
}
return params
}
//‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾
// Template methods
//___________________________________
// tmplPathParam method returns Request Path Param value for the given key.
func tmplPathParam(viewArgs map[string]interface{}, key string) interface{} {
params := viewArgs[KeyViewArgRequestParams].(*ahttp.Params)
return sanatizeValue(params.PathValue(key))
}
// tmplFormParam method returns Request Form value for the given key.
func tmplFormParam(viewArgs map[string]interface{}, key string) interface{} {
params := viewArgs[KeyViewArgRequestParams].(*ahttp.Params)
return sanatizeValue(params.FormValue(key))
}
// tmplQueryParam method returns Request Query String value for the given key.
func tmplQueryParam(viewArgs map[string]interface{}, key string) interface{} {
params := viewArgs[KeyViewArgRequestParams].(*ahttp.Params)
return sanatizeValue(params.QueryValue(key))
}
func bindInitialize(e *Event) {
cfg := AppConfig()
keyPathParamName = cfg.StringDefault("i18n.param_name.path", keyOverrideI18nName)
keyQueryParamName = cfg.StringDefault("i18n.param_name.query", keyOverrideI18nName)
// Content Negotitaion, GitHub #75
isContentNegotiationEnabled = cfg.BoolDefault("request.content_negotiation.enable", false)
acceptedContentTypes, _ = cfg.StringList("request.content_negotiation.accepted")
for idx, v := range acceptedContentTypes {
acceptedContentTypes[idx] = strings.ToLower(v)
if v == allContentTypes {
// when `*/*` is mentioned, don't check the condition
// because it means every content type is allowed
acceptedContentTypes = make([]string, 0)
break
}
}
offeredContentTypes, _ = cfg.StringList("request.content_negotiation.offered")
for idx, v := range offeredContentTypes {
offeredContentTypes[idx] = strings.ToLower(v)
if v == allContentTypes {
// when `*/*` is mentioned, don't check the condition
// because it means every content type is allowed
offeredContentTypes = make([]string, 0)
break
}
}
// Auto Parse and Bind, GitHub #26
requestParsers[ahttp.ContentTypeMultipartForm.Mime] = multipartFormParser
requestParsers[ahttp.ContentTypeForm.Mime] = formParser
autobindPriority = reverseSlice(strings.Split(cfg.StringDefault("request.auto_bind.priority", "PFQ"), ""))
timeFormats, found := cfg.StringList("format.time")
if !found {
timeFormats = []string{
"2006-01-02T15:04:05Z07:00",
"2006-01-02T15:04:05Z",
"2006-01-02 15:04:05",
"2006-01-02"}
}
valpar.TimeFormats = timeFormats
valpar.StructTagName = cfg.StringDefault("request.auto_bind.tag_name", "bind")
}
func init() {
OnStart(bindInitialize)
}