-
Notifications
You must be signed in to change notification settings - Fork 0
/
form.go
141 lines (119 loc) · 2.07 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
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
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
package fork
import (
"bytes"
"html/template"
"net/http"
)
type FormConfig func(Form) error
type Form interface {
Tagged
Creator
Former
Renderer
Informer
Checker
}
type Tagged interface {
Tag() string
}
type Creator interface {
New() Form
Configure(...FormConfig) error
}
type Former interface {
Fields(...Field) []Field
Process(*http.Request)
}
type Renderer interface {
Buffer() *bytes.Buffer
String() string
Render() template.HTML
}
type Informer interface {
Values() map[string]*Value
}
func Checks(cs ...interface{}) FormConfig {
return func(f Form) error {
f.Checks(cs...)
return nil
}
}
func Fields(fs ...Field) FormConfig {
return func(f Form) error {
f.Fields(fs...)
return nil
}
}
func NewForm(tag string, fc ...FormConfig) Form {
nf := &form{
tag: tag,
Checker: NewChecker(),
}
nf.Configure(fc...)
return nf
}
type form struct {
tag string
fields []Field
values map[string]*Value
Checker
}
func (f *form) Tag() string {
return f.tag
}
func (f *form) New() Form {
var newform form = *f
fs := f.fields
newform.fields = nil
for _, field := range fs {
newform.fields = append(newform.fields, field.New())
}
return &newform
}
func (f *form) Configure(fc ...FormConfig) error {
var err error
for _, c := range fc {
err = c(f)
}
return err
}
func (f *form) Fields(fs ...Field) []Field {
f.fields = append(f.fields, fs...)
return f.fields
}
func (f *form) Process(r *http.Request) {
if len(r.PostForm) == 0 {
r.ParseForm()
}
for _, fd := range f.Fields() {
fd.Set(r)
}
}
func (f *form) Buffer() *bytes.Buffer {
b := new(bytes.Buffer)
for _, fd := range f.Fields() {
fb, err := fd.Bytes(fd)
if err == nil {
b.ReadFrom(fb)
}
}
return b
}
func (f *form) String() string {
return f.Buffer().String()
}
func (f *form) Render() template.HTML {
return template.HTML(f.String())
}
func (f *form) mkvalues() {
f.values = make(map[string]*Value)
for _, fd := range f.fields {
f.values[fd.Name()] = fd.Get()
}
}
func (f *form) Values() map[string]*Value {
if f.values == nil {
f.mkvalues()
}
return f.values
}