forked from gofiber/fiber
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbind.go
More file actions
586 lines (488 loc) · 17.6 KB
/
Copy pathbind.go
File metadata and controls
586 lines (488 loc) · 17.6 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
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
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
package fiber
import (
"encoding/json"
"errors"
"fmt"
"reflect"
"slices"
"strings"
"sync"
"github.com/gofiber/fiber/v3/binder"
"github.com/gofiber/fiber/v3/internal/nilerror"
"github.com/gofiber/schema"
"github.com/gofiber/utils/v2"
utilsbytes "github.com/gofiber/utils/v2/bytes"
)
// CustomBinder An interface to register custom binders.
type CustomBinder interface {
Name() string
MIMETypes() []string
Parse(c Ctx, out any) error
}
// StructValidator is an interface to register custom struct validator for binding.
type StructValidator interface {
Validate(out any) error
}
var bindPool = sync.Pool{
New: func() any {
return &Bind{
shouldSkipErrHandling: true,
}
},
}
// Bind provides helper methods for binding request data to Go values.
// By default (manual mode), parsing failures are returned as *BindError; use errors.As to extract source and field details.
// With WithAutoHandling(), parsing failures set HTTP 400 and return *Error instead.
type Bind struct {
ctx Ctx
shouldSkipErrHandling bool
shouldSkipValidation bool
}
// BindError source constants for BindError.Source.
const (
BindSourceURI = "uri"
BindSourceQuery = "query"
BindSourceHeader = "header"
BindSourceCookie = "cookie"
BindSourceBody = "body"
BindSourceRespHeader = "respHeader"
)
// BindError wraps a binding failure with the source and field that failed.
// Use errors.As(err, &be) to extract it when you need to branch on source
// (e.g. 404 for URI vs 400 for body).
type BindError struct {
Err error // underlying error; use errors.As to inspect
Source string // binding source: uri, query, body, header, cookie, or respHeader (see BindSource* constants)
Field string // struct field or tag key that failed (best-effort, may be empty)
}
func (e *BindError) Error() string {
if e.Field != "" {
return fmt.Sprintf("bind %q from %s: %v", e.Field, e.Source, e.Err)
}
return fmt.Sprintf("bind from %s: %v", e.Source, e.Err)
}
func (e *BindError) Unwrap() error {
return e.Err
}
func extractFieldFromError(err error) string {
var convErr schema.ConversionError
if errors.As(err, &convErr) {
return convErr.Key
}
var unknownKey schema.UnknownKeyError
if errors.As(err, &unknownKey) {
return unknownKey.Key
}
var emptyField schema.EmptyFieldError
if errors.As(err, &emptyField) {
return emptyField.Key
}
var multiErr schema.MultiError
if errors.As(err, &multiErr) {
for k := range multiErr {
return k
}
}
var unmarshalErr *json.UnmarshalTypeError
if errors.As(err, &unmarshalErr) {
return unmarshalErr.Field
}
return ""
}
func newBindError(source string, raw error) *BindError {
return &BindError{Source: source, Field: extractFieldFromError(raw), Err: raw}
}
// AcquireBind returns Bind reference from bind pool.
func AcquireBind() *Bind {
b, ok := bindPool.Get().(*Bind)
if !ok {
panic(errBindPoolTypeAssertion)
}
return b
}
// ReleaseBind returns b acquired via Bind to bind pool.
func ReleaseBind(b *Bind) {
b.release()
bindPool.Put(b)
}
// releasePooledBinder resets a binder and returns it to its pool.
// It should be used with defer to ensure proper cleanup of pooled binders.
func releasePooledBinder[T interface{ Reset() }](pool *sync.Pool, bind T) {
bind.Reset()
binder.PutToThePool(pool, bind)
}
func (b *Bind) release() {
b.ctx = nil
b.shouldSkipErrHandling = true
b.shouldSkipValidation = false
}
// WithoutAutoHandling If you want to handle binder errors manually, you can use `WithoutAutoHandling`.
// It's default behavior of binder.
func (b *Bind) WithoutAutoHandling() *Bind {
b.shouldSkipErrHandling = true
return b
}
// WithAutoHandling If you want to handle binder errors automatically, you can use `WithAutoHandling`.
// If there's an error, it will return the error and set HTTP status to `400 Bad Request`.
// You must still return on error explicitly
func (b *Bind) WithAutoHandling() *Bind {
b.shouldSkipErrHandling = false
return b
}
// SkipValidation enables or disables struct validation for the current bind chain.
func (b *Bind) SkipValidation(skip bool) *Bind {
b.shouldSkipValidation = skip
return b
}
// Check WithAutoHandling/WithoutAutoHandling errors and return it by usage.
func (b *Bind) returnErr(err error) error {
if nilerror.IsNil(err) {
return nil
}
var fiberErr *Error
matched := errors.As(err, &fiberErr)
if matched && fiberErr == nil {
return nil
}
if b.shouldSkipErrHandling {
return err
}
b.ctx.Status(StatusBadRequest)
return NewError(StatusBadRequest, "Bad request: "+err.Error())
}
// returnBindErr runs returnErr and, if the result is not a *Error, wraps it in *BindError.
// Use for binding parse failures; use returnErr directly for Custom and validation errors.
func (b *Bind) returnBindErr(err error, source string) error {
if retErr := b.returnErr(err); retErr != nil {
var fiberErr *Error
if errors.As(retErr, &fiberErr) && fiberErr != nil {
return fiberErr
}
return newBindError(source, retErr)
}
return nil
}
// Struct validation.
func (b *Bind) validateStruct(out any) error {
if b.shouldSkipValidation {
return nil
}
validator := b.ctx.App().config.StructValidator
if validator == nil {
return nil
}
t := reflect.TypeOf(out)
if t == nil {
return nil
}
// Unwrap pointers (e.g. *T, **T) to inspect the underlying destination type.
for t.Kind() == reflect.Pointer {
t = t.Elem()
}
if t.Kind() != reflect.Struct {
return nil
}
return validator.Validate(out)
}
// Custom To use custom binders, you have to use this method.
// You can register them from RegisterCustomBinder method of Fiber instance.
// They're checked by name, if it's not found, it will return an error.
// NOTE: WithAutoHandling/WithAutoHandling is still valid for Custom binders.
func (b *Bind) Custom(name string, dest any) error {
binders := b.ctx.App().customBinders
for _, customBinder := range binders {
if customBinder.Name() == name {
if err := b.returnBindErr(customBinder.Parse(b.ctx, dest), name); err != nil {
return err
}
return b.validateStruct(dest)
}
}
return ErrCustomBinderNotFound
}
// Header binds the request header strings into the struct, map[string]string and map[string][]string.
// Returns *BindError on parse failure (manual mode) or *Error with status 400 (auto-handling mode).
func (b *Bind) Header(out any) error {
bind := binder.GetFromThePool[*binder.HeaderBinding](&binder.HeaderBinderPool)
bind.EnableSplitting = b.ctx.App().config.EnableSplittingOnParsers
defer releasePooledBinder(&binder.HeaderBinderPool, bind)
if err := b.returnBindErr(bind.Bind(b.ctx.Request(), out), BindSourceHeader); err != nil {
return err
}
return b.validateStruct(out)
}
// RespHeader binds the response header strings into the struct, map[string]string and map[string][]string.
// Returns *BindError on parse failure (manual mode) or *Error with status 400 (auto-handling mode).
func (b *Bind) RespHeader(out any) error {
bind := binder.GetFromThePool[*binder.RespHeaderBinding](&binder.RespHeaderBinderPool)
bind.EnableSplitting = b.ctx.App().config.EnableSplittingOnParsers
defer releasePooledBinder(&binder.RespHeaderBinderPool, bind)
if err := b.returnBindErr(bind.Bind(b.ctx.Response(), out), BindSourceRespHeader); err != nil {
return err
}
return b.validateStruct(out)
}
// Cookie binds the request cookie strings into the struct, map[string]string and map[string][]string.
// Returns *BindError on parse failure (manual mode) or *Error with status 400 (auto-handling mode).
// NOTE: If your cookie is like key=val1,val2; they'll be bound as a slice if your map is map[string][]string. Else, it'll use last element of cookie.
func (b *Bind) Cookie(out any) error {
bind := binder.GetFromThePool[*binder.CookieBinding](&binder.CookieBinderPool)
bind.EnableSplitting = b.ctx.App().config.EnableSplittingOnParsers
defer releasePooledBinder(&binder.CookieBinderPool, bind)
if err := b.returnBindErr(bind.Bind(&b.ctx.RequestCtx().Request, out), BindSourceCookie); err != nil {
return err
}
return b.validateStruct(out)
}
// Query binds the query string into the struct, map[string]string and map[string][]string.
// Returns *BindError on parse failure (manual mode) or *Error with status 400 (auto-handling mode).
func (b *Bind) Query(out any) error {
bind := binder.GetFromThePool[*binder.QueryBinding](&binder.QueryBinderPool)
bind.EnableSplitting = b.ctx.App().config.EnableSplittingOnParsers
defer releasePooledBinder(&binder.QueryBinderPool, bind)
if err := b.returnBindErr(bind.Bind(&b.ctx.RequestCtx().Request, out), BindSourceQuery); err != nil {
return err
}
return b.validateStruct(out)
}
// JSON binds the body string into the struct.
// Returns *BindError on parse failure (manual mode) or *Error with status 400 (auto-handling mode).
func (b *Bind) JSON(out any) error {
bind := binder.GetFromThePool[*binder.JSONBinding](&binder.JSONBinderPool)
bind.JSONDecoder = b.ctx.App().Config().JSONDecoder
defer releasePooledBinder(&binder.JSONBinderPool, bind)
if err := b.returnBindErr(bind.Bind(b.ctx.Body(), out), BindSourceBody); err != nil {
return err
}
return b.validateStruct(out)
}
// CBOR binds the body string into the struct.
// Returns *BindError on parse failure (manual mode) or *Error with status 400 (auto-handling mode).
func (b *Bind) CBOR(out any) error {
bind := binder.GetFromThePool[*binder.CBORBinding](&binder.CBORBinderPool)
bind.CBORDecoder = b.ctx.App().Config().CBORDecoder
defer releasePooledBinder(&binder.CBORBinderPool, bind)
if err := b.returnBindErr(bind.Bind(b.ctx.Body(), out), BindSourceBody); err != nil {
return err
}
return b.validateStruct(out)
}
// XML binds the body string into the struct.
// Returns *BindError on parse failure (manual mode) or *Error with status 400 (auto-handling mode).
func (b *Bind) XML(out any) error {
bind := binder.GetFromThePool[*binder.XMLBinding](&binder.XMLBinderPool)
bind.XMLDecoder = b.ctx.App().config.XMLDecoder
defer releasePooledBinder(&binder.XMLBinderPool, bind)
if err := b.returnBindErr(bind.Bind(b.ctx.Body(), out), BindSourceBody); err != nil {
return err
}
return b.validateStruct(out)
}
// Form binds the form into the struct, map[string]string and map[string][]string.
// Returns *BindError on parse failure (manual mode) or *Error with status 400 (auto-handling mode).
// If Content-Type is "application/x-www-form-urlencoded" or "multipart/form-data", it will bind the form values.
// Multipart file fields are supported using *multipart.FileHeader, []*multipart.FileHeader, or *[]*multipart.FileHeader.
func (b *Bind) Form(out any) error {
bind := binder.GetFromThePool[*binder.FormBinding](&binder.FormBinderPool)
bind.EnableSplitting = b.ctx.App().config.EnableSplittingOnParsers
bind.MaxBodySize = b.ctx.App().config.BodyLimit
defer releasePooledBinder(&binder.FormBinderPool, bind)
if err := b.returnBindErr(bind.Bind(&b.ctx.RequestCtx().Request, out), BindSourceBody); err != nil {
return err
}
return b.validateStruct(out)
}
// URI binds the route parameters into the struct, map[string]string and map[string][]string.
// Returns *BindError on parse failure (manual mode) or *Error with status 400 (auto-handling mode).
func (b *Bind) URI(out any) error {
bind := binder.GetFromThePool[*binder.URIBinding](&binder.URIBinderPool)
defer releasePooledBinder(&binder.URIBinderPool, bind)
if err := b.returnBindErr(bind.Bind(b.ctx.Route().Params, b.ctx.Params, out), BindSourceURI); err != nil {
return err
}
return b.validateStruct(out)
}
// MsgPack binds the body string into the struct.
// Returns *BindError on parse failure (manual mode) or *Error with status 400 (auto-handling mode).
func (b *Bind) MsgPack(out any) error {
bind := binder.GetFromThePool[*binder.MsgPackBinding](&binder.MsgPackBinderPool)
bind.MsgPackDecoder = b.ctx.App().Config().MsgPackDecoder
defer releasePooledBinder(&binder.MsgPackBinderPool, bind)
if err := b.returnBindErr(bind.Bind(b.ctx.Body(), out), BindSourceBody); err != nil {
return err
}
return b.validateStruct(out)
}
// Body binds the request body into the struct, map[string]string and map[string][]string.
// Returns *BindError on parse failure (manual mode) or *Error with status 400 (auto-handling mode).
// It supports decoding the following content types based on the Content-Type header:
// application/json, application/xml, application/x-www-form-urlencoded, multipart/form-data
// If none of the content types above are matched, it'll take a look custom binders by checking the MIMETypes() method of custom binder.
// If there is no custom binder for mime type of body, it will return a ErrUnprocessableEntity error.
func (b *Bind) Body(out any) error {
// Get content-type
ctype := utils.UnsafeString(utilsbytes.UnsafeToLower(b.ctx.RequestCtx().Request.Header.ContentType()))
ctype = binder.FilterFlags(utils.ParseVendorSpecificContentType(ctype))
// Check custom binders
binders := b.ctx.App().customBinders
for _, customBinder := range binders {
if slices.Contains(customBinder.MIMETypes(), ctype) {
if err := b.returnBindErr(customBinder.Parse(b.ctx, out), BindSourceBody); err != nil {
return err
}
return b.validateStruct(out)
}
}
// Parse body accordingly
switch ctype {
case MIMEApplicationJSON:
return b.JSON(out)
case MIMEApplicationMsgPack:
return b.MsgPack(out)
case MIMETextXML, MIMEApplicationXML:
return b.XML(out)
case MIMEApplicationCBOR:
return b.CBOR(out)
case MIMEApplicationForm, MIMEMultipartForm:
return b.Form(out)
}
// No suitable content type found
return ErrUnprocessableEntity
}
type bindSource int
const (
sourceURI bindSource = iota
sourceBody
sourceQuery
sourceHeader
sourceCookie
)
type cachedPrecedence struct {
err error
sources []bindSource
}
var bindingPrecedenceCache sync.Map // map[reflect.Type]cachedPrecedence
func getBindingPrecedence(t reflect.Type) ([]bindSource, error) {
if cached, ok := bindingPrecedenceCache.Load(t); ok {
if cp, ok := cached.(cachedPrecedence); ok {
return cp.sources, cp.err
}
}
var precedence []bindSource
var tagFound bool
for i := range t.NumField() {
if tag := t.Field(i).Tag.Get("binding_source"); tag != "" {
if tagFound {
err := fmt.Errorf("multiple binding_source tags found on struct %s", t.Name())
bindingPrecedenceCache.Store(t, cachedPrecedence{err: err, sources: nil})
return nil, err
}
tagFound = true
parts := strings.SplitSeq(tag, ",")
for p := range parts {
sourceName := strings.TrimSpace(p)
if sourceName == "" {
continue
}
var source bindSource
switch sourceName {
case "uri":
source = sourceURI
case "body":
source = sourceBody
case "query":
source = sourceQuery
case "header":
source = sourceHeader
case "cookie":
source = sourceCookie
default:
err := fmt.Errorf("unknown binding_source %q", sourceName)
bindingPrecedenceCache.Store(t, cachedPrecedence{err: err, sources: nil})
return nil, err
}
// check for duplicates
if !slices.Contains(precedence, source) {
precedence = append(precedence, source)
}
}
}
}
bindingPrecedenceCache.Store(t, cachedPrecedence{err: nil, sources: precedence})
return precedence, nil
}
// All binds values from URI params, the request body, the query string,
// headers, and cookies into the provided struct in precedence order.
// Returns *BindError on parse failure (manual mode) or *Error with status 400 (auto-handling mode).
func (b *Bind) All(out any) error {
outVal := reflect.ValueOf(out)
if outVal.Kind() != reflect.Pointer || outVal.Elem().Kind() != reflect.Struct {
return ErrUnprocessableEntity
}
outElem := outVal.Elem()
sources := make([]func(any) error, 0, 5)
customPrecedence, err := getBindingPrecedence(outElem.Type())
if err != nil {
// Note: A malformed binding_source tag is a programmer error, not a client error.
// Returning the raw error here bypasses b.returnErr, intentionally resulting in a 500
// rather than a 400 even in auto-handling mode.
return err
}
hasBody := len(b.ctx.Request().Body()) > 0 && len(b.ctx.RequestCtx().Request.Header.ContentType()) > 0
if len(customPrecedence) > 0 {
for _, source := range customPrecedence {
switch source {
case sourceURI:
sources = append(sources, b.URI)
case sourceBody:
if hasBody {
sources = append(sources, b.Body)
}
case sourceQuery:
sources = append(sources, b.Query)
case sourceHeader:
sources = append(sources, b.Header)
case sourceCookie:
sources = append(sources, b.Cookie)
}
}
} else {
// Precedence: URL Params -> Body -> Query -> Headers -> Cookies
sources = append(sources, b.URI)
// Check if both Body and Content-Type are set
if hasBody {
sources = append(sources, b.Body)
}
sources = append(sources, b.Query, b.Header, b.Cookie)
}
prevSkip := b.shouldSkipValidation
b.shouldSkipValidation = true
// TODO: Create WithOverrideEmptyValues
// Bind from each source, but only update unset fields
for _, bindFunc := range sources {
tempStruct := reflect.New(outElem.Type()).Interface()
if err := bindFunc(tempStruct); err != nil {
b.shouldSkipValidation = prevSkip
return err
}
tempStructVal := reflect.ValueOf(tempStruct).Elem()
mergeStruct(outElem, tempStructVal)
}
b.shouldSkipValidation = prevSkip
return b.returnErr(b.validateStruct(out))
}
func mergeStruct(dst, src reflect.Value) {
dstFields := dst.NumField()
for i := range dstFields {
dstField := dst.Field(i)
srcField := src.Field(i)
// Skip if the destination field is already set.
// Use reflect.Value.IsZero() directly to avoid Interface() boxing
// and reflect.ValueOf() overhead — saves ~12 allocs/op on Bind.All().
if dstField.IsZero() {
if dstField.CanSet() && srcField.IsValid() {
dstField.Set(srcField)
}
}
}
}