This repository has been archived by the owner on Sep 28, 2019. It is now read-only.
/
forms.go
92 lines (82 loc) · 2.3 KB
/
forms.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
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
package httpc
import (
"encoding/json"
"mime"
"net/http"
"github.com/gorilla/schema"
)
// A Form represents a form with validation.
type Form interface {
// Validate sanitizes and validates the form.
Validate() error
}
// UploadForm represents a form with a maximum file upload size.
type UploadForm interface {
// MaxUploadSize returns the maximum file upload size in bytes.
MaxUploadSize() int64
}
// Validate decodes, sanitizes and validates the request body
// and stores the result in to the value pointed to by form.
func Validate(req *http.Request, form Form) error {
v := req.Header.Get("Content-Type")
media, _, err := mime.ParseMediaType(v)
if err != nil {
return err
}
switch media {
case "application/json":
return ValidateJSON(req, form)
case "multipart/form-data":
return ValidateMultipart(req, form)
}
return ValidateForm(req, form)
}
// decoder decodes a struct with form values.
// The decoder caches struct meta data and can be shared safely.
var decoder = schema.NewDecoder()
// ValidateForm decodes, sanitizes and validates the request
// body as a form and stores the result in the value pointed
// to by form.
func ValidateForm(req *http.Request, form Form) error {
err := req.ParseForm()
if err != nil {
return err
}
err = decoder.Decode(form, req.PostForm)
if err != nil {
return err
}
return form.Validate()
}
// ValidateJSON decodes, sanitizes and validates the request
// body as JSON and stores the result in the value pointed
// to by form.
func ValidateJSON(req *http.Request, form Form) error {
defer req.Body.Close()
err := json.NewDecoder(req.Body).Decode(form)
if err != nil {
return err
}
return form.Validate()
}
// DefaultMaxUploadSize is the default maximum file upload size in bytes.
const DefaultMaxUploadSize int64 = 32 << 20 // 32 MB
// ValidateMultipart decodes, sanitizes and validates the request
// body as multipart/form-data and stores the result in the value
// pointed to by form.
func ValidateMultipart(req *http.Request, form Form) error {
maxUploadSize := DefaultMaxUploadSize
uf, ok := form.(UploadForm)
if ok {
maxUploadSize = uf.MaxUploadSize()
}
err := req.ParseMultipartForm(maxUploadSize)
if err != nil {
return err
}
err = decoder.Decode(form, req.MultipartForm.Value)
if err != nil {
return err
}
return form.Validate()
}