-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathinput.go
More file actions
98 lines (82 loc) · 2.02 KB
/
input.go
File metadata and controls
98 lines (82 loc) · 2.02 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
package binder
import (
"encoding/json"
"encoding/xml"
"errors"
"fmt"
"net/http"
"net/url"
. "github.com/gota33/http-binder/internal"
)
type StringSliceUnmarshaler = IStringSliceUnmarshaler
type UriParamGetter func(req *http.Request, key string) string
type Input interface {
BindInput(req *http.Request, v any) error
}
type input struct {
InputConfig
}
type InputConfig struct {
UriParamGetter UriParamGetter
}
func NewInput(c InputConfig) Input {
return input{InputConfig: c}
}
func (b input) BindInput(req *http.Request, v any) (err error) {
defer func() {
if err != nil {
err = fmt.Errorf("input binder: %w", err)
}
}()
if req.Body != nil {
defer func() { _ = req.Body.Close() }()
}
acc, err := NewAccessor(v)
if err != nil {
return
}
var bodyErr error
switch GetContentType(req.Header.Get("Content-Type")) {
case ContentTypeForm:
bodyErr = req.ParseForm()
case ContentTypeJSON:
bodyErr = json.NewDecoder(req.Body).Decode(v)
case ContentTypeXML:
bodyErr = xml.NewDecoder(req.Body).Decode(v)
}
return errors.Join(
bodyErr,
b.bindValues(acc, TagQuery, req.URL.Query()),
b.bindValues(acc, TagForm, req.PostForm),
b.bindHeader(acc, req.Header),
b.bindUriParam(acc, req),
)
}
func (b input) bindValues(acc Accessor, tagType TagType, values url.Values) error {
var errs []error
for field, arr := range values {
if err := acc.Set(tagType, field, arr...); err != nil {
errs = append(errs, err)
}
}
return errors.Join(errs...)
}
func (b input) bindHeader(acc Accessor, header http.Header) error {
var errs []error
for name, arr := range header {
name = http.CanonicalHeaderKey(name)
if err := acc.Set(TagHeader, name, arr...); err != nil {
errs = append(errs, err)
}
}
return errors.Join(errs...)
}
func (b input) bindUriParam(acc Accessor, req *http.Request) error {
fields := acc.GetFields(TagUri)
errs := make([]error, len(fields))
for i, field := range fields {
value := b.UriParamGetter(req, field)
errs[i] = acc.Set(TagUri, field, value)
}
return errors.Join(errs...)
}