-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathform.go
70 lines (58 loc) · 1.8 KB
/
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
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
package legit
import (
"errors"
"io"
"net/http"
)
var (
// ErrEncoding is returned when a matching decoder is not found for
// the encoding.
ErrEncoding = errors.New("unknown encoding")
)
// Form implements the decoding and validation of user data from readers
// and HTTP requests
type Form struct {
Legit Legit
Decoders Decoders
}
var form = NewForm()
// NewForm returns a Form assignment with the default Legit configuration and
// a JSON decoder
func NewForm() Form {
return Form{
Legit: New(),
Decoders: Decoders{JSON{}},
}
}
// ParseAndValidate first decodes a reader using the first decoder matching the
// given mime type, then applies validation to the collected input
func ParseAndValidate(r io.Reader, mime string, dst interface{}) error {
return form.ParseAndValidate(r, mime, dst)
}
// ParseAndValidate first decodes a reader using the first decoder matching the
// given mime type, then applies validation to the collected input
func (f Form) ParseAndValidate(r io.Reader, mime string, dst interface{}) error {
dec := f.Decoders.Match(mime)
if dec == nil {
return ErrEncoding
}
err := dec.Decode(r, dst)
if err != nil {
return err
}
err = f.Legit.Validate(dst)
if err != nil {
return err
}
return nil
}
// ParseRequestAndValidate is the same as ParseAndValidate accepting a HTTP
// request for the reader and using the "Content-Type" header for the MIME type
func ParseRequestAndValidate(r *http.Request, dst interface{}) error {
return form.ParseRequestAndValidate(r, dst)
}
// ParseRequestAndValidate is the same as ParseAndValidate accepting a HTTP
// request for the reader and using the "Content-Type" header for the MIME type
func (f Form) ParseRequestAndValidate(r *http.Request, dst interface{}) error {
return f.ParseAndValidate(r.Body, r.Header.Get("Content-Type"), dst)
}