-
Notifications
You must be signed in to change notification settings - Fork 0
/
decode_type.go
66 lines (55 loc) · 2.7 KB
/
decode_type.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
package inreq
import (
"net/http"
"github.com/rrgmc/instruct"
inoptions "github.com/rrgmc/instruct/options"
)
// TypeDecoder decodes http requests to structs.
type TypeDecoder[T any] struct {
dec *instruct.TypeDecoder[*http.Request, DecodeContext, T]
defaultOptions typeDefaultOptions
}
// NewTypeDecoder creates a Decoder instance with the default decode operations (query, path, header, form, body).
func NewTypeDecoder[T any](options ...TypeDefaultOption) *TypeDecoder[T] {
return NewCustomTypeDecoder[T](inoptions.ConcatOptionsBefore[TypeDefaultOption](options, WithDefaultDecodeOperations())...)
}
// NewCustomTypeDecoder creates a Decoder instance without any decode operations. At least one must be added for
// decoding to work.
func NewCustomTypeDecoder[T any](options ...TypeDefaultOption) *TypeDecoder[T] {
optns := defaultTypeDefaultOptions()
optns.apply(options...)
return &TypeDecoder[T]{
dec: instruct.NewTypeDecoder[*http.Request, DecodeContext, T](optns.options),
defaultOptions: optns,
}
}
// Decode decodes the http request to the struct passed in "data".
func (d *TypeDecoder[T]) Decode(r *http.Request, options ...TypeDecodeOption) (T, error) {
optns := defaultDecodeOptions()
optns.applyType(options...)
optns.options.Ctx = &decodeContext{
DefaultDecodeContext: instruct.NewDefaultDecodeContext(d.defaultOptions.options.FieldNameMapper),
pathValue: d.defaultOptions.pathValue,
bodyDecoder: d.defaultOptions.bodyDecoder,
sliceSplitSeparator: d.defaultOptions.sliceSplitSeparator,
allowReadBody: optns.allowReadBody,
ensureAllQueryUsed: optns.ensureAllQueryUsed,
ensureAllFormUsed: optns.ensureAllFormUsed,
}
return d.dec.Decode(r, optns.options)
}
// DecodeType decodes the http request to the struct passed in "data" using NewDecoder.
// Any map tags set using WithMapTags will be considered as "default" map tags. (see WithDefaultMapTags for details).
func DecodeType[T any](r *http.Request, options ...AnyTypeOption) (T, error) {
options = inoptions.ConcatOptionsBefore[AnyTypeOption](options,
WithDefaultDecodeOperations(),
)
return NewTypeDecoder[T](inoptions.ExtractOptions[TypeDefaultOption](options)...).Decode(r,
inoptions.ExtractOptions[TypeDecodeOption](options)...)
}
// CustomDecodeType decodes the http request to the struct passed in "data" using NewCustomDecoder.
// Any map tags set using WithMapTags will be considered as "default" map tags. (see WithDefaultMapTags for details).
func CustomDecodeType[T any](r *http.Request, options ...AnyTypeOption) (T, error) {
return NewTypeDecoder[T](inoptions.ExtractOptions[TypeDefaultOption](options)...).Decode(r,
inoptions.ExtractOptions[TypeDecodeOption](options)...)
}