-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdecode.go
70 lines (59 loc) · 2.68 KB
/
decode.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
package inreq
import (
"net/http"
"github.com/rrgmc/instruct"
inoptions "github.com/rrgmc/instruct/options"
)
// Decoder decodes http requests to structs.
type Decoder struct {
dec *instruct.Decoder[*http.Request, DecodeContext]
defaultOptions defaultOptions
}
// NewDecoder creates a Decoder instance with the default decode operations (query, path, header, form, body).
func NewDecoder(options ...DefaultOption) *Decoder {
return NewCustomDecoder(inoptions.ConcatOptionsBefore[DefaultOption](options, WithDefaultDecodeOperations())...)
}
// NewCustomDecoder creates a Decoder instance without any decode operations. At least one must be added for
// decoding to work.
func NewCustomDecoder(options ...DefaultOption) *Decoder {
optns := defaultDefaultOptions()
optns.apply(options...)
return &Decoder{
dec: instruct.NewDecoder[*http.Request, DecodeContext](optns.options),
defaultOptions: optns,
}
}
// Decode decodes the http request to the struct passed in "data".
func (d *Decoder) Decode(r *http.Request, data any, options ...DecodeOption) error {
optns := defaultDecodeOptions()
optns.apply(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, data, optns.options)
}
// Decode 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 Decode(r *http.Request, data any, options ...AnyOption) error {
options = inoptions.ConcatOptionsBefore[AnyOption](options,
withUseDecodeMapTagsAsDefault(true),
WithDefaultDecodeOperations(),
)
return NewDecoder(inoptions.ExtractOptions[DefaultOption](options)...).Decode(r, data,
inoptions.ExtractOptions[DecodeOption](options)...)
}
// CustomDecode 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 CustomDecode(r *http.Request, data any, options ...AnyOption) error {
options = inoptions.ConcatOptionsBefore[AnyOption](options,
withUseDecodeMapTagsAsDefault(true),
)
return NewDecoder(inoptions.ExtractOptions[DefaultOption](options)...).Decode(r, data,
inoptions.ExtractOptions[DecodeOption](options)...)
}