-
Notifications
You must be signed in to change notification settings - Fork 16
/
form.go
48 lines (38 loc) · 947 Bytes
/
form.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
package binding
import (
"net/http"
"net/url"
"github.com/monoculum/formam"
)
// FormTagName for decode form data
var FormTagName = "form"
// FormBinder binding Form/url.Values data to struct
type FormBinder struct {
TagName string
}
// Name get name
func (FormBinder) Name() string {
return "form"
}
// Bind Form data from http.Request
func (b FormBinder) Bind(r *http.Request, ptr any) error {
err := r.ParseForm()
if err != nil {
return err
}
return DecodeUrlValues(r.Form, ptr, b.TagName)
}
// BindValues data from url.Values
func (b FormBinder) BindValues(values url.Values, ptr any) error {
return DecodeUrlValues(values, ptr, b.TagName)
}
// DecodeUrlValues data to struct
func DecodeUrlValues(values map[string][]string, ptr any, tagName string) error {
dec := formam.NewDecoder(&formam.DecoderOptions{
TagName: tagName,
})
if err := dec.Decode(values, ptr); err != nil {
return err
}
return Validate(ptr)
}