-
Notifications
You must be signed in to change notification settings - Fork 1
/
form.go
65 lines (58 loc) · 1.33 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
package rex
import (
"fmt"
"mime/multipart"
"net/http"
)
const (
defaultMaxMemory = 32 << 20 // 32 MB
)
// A Form to handle request form data.
type Form struct {
R *http.Request
}
// Has checks the value for the key whether exists.
func (form *Form) Has(key string) bool {
r := form.R
if m := r.Method; m == "POST" || m == "PUT" || m == "PATCH" {
if r.PostForm == nil {
r.ParseMultipartForm(defaultMaxMemory)
}
_, ok := r.PostForm[key]
if ok {
return true
}
}
if r.Form == nil {
r.ParseMultipartForm(defaultMaxMemory)
}
_, ok := r.Form[key]
return ok
}
// Value returns the value for the key.
func (form *Form) Value(key string) string {
r := form.R
if m := r.Method; m == "POST" || m == "PUT" || m == "PATCH" {
if r.PostForm == nil {
r.ParseMultipartForm(defaultMaxMemory)
}
if vs, ok := r.PostForm[key]; ok {
if len(vs) > 0 {
return vs[0]
}
return ""
}
}
return r.FormValue(key)
}
// File returns the first file for the provided form key.
func (form *Form) File(key string) (multipart.File, *multipart.FileHeader, error) {
return form.R.FormFile(key)
}
// Require returns the value for the key, if the value is empty, it will panic.
func (form *Form) Require(key string) string {
if !form.Has(key) {
panic(&invalid{400, fmt.Sprintf("require form field '%s'", key)})
}
return form.Value(key)
}