/
forms.go
339 lines (281 loc) · 7.65 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
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
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
package uos
import (
"fmt"
"net/http"
"net/url"
"strconv"
"strings"
)
// FormSpec describes the interface every web application form must implement.
type FormSpec interface {
// Name returns the short name of the form. The form is available at '/forms/<name>'.
Name() string
}
// FormSpecRead must be implemented by a web application form to support GET requests.
type FormSpecRead interface {
// Read returns the list of form items. If an id is specified, the form items for an existing
// entity is returned.
Read(id string) (FormItems, error)
}
// FormSpecSave must be implemented by a web application form to support POST requests.
type FormSpecSave interface {
// Read returns the list of form items. If an id is specified, the form items for an existing
// entity is returned.
Read(id string) (FormItems, error)
// Save writes the specified items to the database.
Save(id string, items FormItems) (*ResponseAction, error)
}
// FormSpecDelete must be implemented by a web application form to support DELETE requests.
type FormSpecDelete interface {
// Delete removes the specified item from the database.
Delete(id string) (*ResponseAction, error)
}
// FormItem describes a single form entry, e.g. an input box.
type FormItem struct {
ID string
InputType string
InputTypeHTML string
Name string
Value string
DefaultValue string
Constraints *FormItemConstraints
Class string
Placeholder string
Min string
Max string
Label string
Help string
HelpClass string
Message string
MessageClass string
IsHorizontal bool
IsHidden bool
HasFocus bool
}
type FormItemConstraints struct {
IsMandatory bool
IsNumber bool
MinValue float64
MaxValue float64
MinLength int
MaxLength int
Regexp string
}
func (fi *FormItem) validate(value string) bool {
if fi.Constraints == nil {
return true
}
// check constraints ..
// .. field required?
if len(value) == 0 && fi.Constraints.IsMandatory {
fi.Help = "required"
fi.HelpClass = "is-danger"
return false
}
// .. value length
if len(value) < fi.Constraints.MinLength {
fi.Help = fmt.Sprintf("too short - at least %d characters", fi.Constraints.MinLength)
fi.HelpClass = "is-danger"
return false
}
if fi.Constraints.MaxLength > 0 && len(value) > fi.Constraints.MaxLength {
fi.Help = fmt.Sprintf("too long - at most %d characters", fi.Constraints.MaxLength)
fi.HelpClass = "is-danger"
return false
}
// .. number? -> check min/max
if fi.Constraints.IsNumber {
f, err := strconv.ParseFloat(value, 64)
if err != nil {
fi.Help = fmt.Sprint("not a number")
fi.HelpClass = "is-danger"
return false
}
if f < fi.Constraints.MinValue {
fi.Help = fmt.Sprintf("value too small, must be >= %f", fi.Constraints.MinValue)
fi.HelpClass = "is-danger"
return false
}
if f > fi.Constraints.MaxValue {
fi.Help = fmt.Sprintf("value too big, must be <= %f", fi.Constraints.MaxValue)
fi.HelpClass = "is-danger"
return false
}
}
// TODO: check regular expression
return true
}
// FormItems is a list of form items.
type FormItems []FormItem
func (fi *FormItems) setValues(v url.Values) bool {
var isValid = true
for i, item := range *fi {
// get provided (URL) value
value := strings.TrimSpace(v.Get(item.Name))
if value == "" {
value = item.DefaultValue
}
// validate item
itemIsValid := item.validate(value)
// update item ..
// .. set value (independent of validity)
item.Value = value
// .. set focus on first invalid form item
item.HasFocus = isValid && !itemIsValid
(*fi)[i] = item
// update overall validation result
isValid = isValid && itemIsValid
}
return isValid
}
func (fi *FormItems) Get(name string) *FormItem {
for _, item := range *fi {
if item.Name == name {
return &item
}
}
return nil
}
// FormHandler returns a handler for the "/forms/" route providing the specified forms.
// The handler can be activated using RegisterAppRequestHandlers.
func FormHandler(forms ...FormSpec) AppRequestHandlerMapping {
return AppRequestHandlerMapping{
Route: "/forms/",
Handler: getFormsHandlerFunc(forms),
}
}
func getFormsHandlerFunc(forms []FormSpec) AppRequestHandler {
nameToSpec := map[string]FormSpec{}
for _, f := range forms {
nameToSpec[f.Name()] = f
Log.DebugContext("register form spec", LogContext{"name": f.Name()})
}
return func(w http.ResponseWriter, r *http.Request) {
// determine form
formName := getElementName("forms", r.URL.Path)
Log.DebugContextR(
r, "handle form",
LogContext{
"name": formName,
"method": r.Method,
},
)
formSpec, ok := nameToSpec[formName]
if !ok {
RespondNotFound(w)
return
}
// prepare request processing (URL form data might be empty)
var (
id = r.Form.Get("id")
submitButton = r.Form.Get("btn")
csrf = r.Form.Get("csrf")
)
// process request
switch r.Method {
case http.MethodGet:
// does the form support GET method?
formRead, ok := formSpec.(FormSpecRead)
if !ok {
RespondNotImplemented(w)
return
}
items, err := formRead.Read(id)
if err != nil {
handleFormError(w, r, "could not read/initialize form", err)
return
}
renderForm(w, r, formName, items, submitButton, "")
case http.MethodPost:
// does the form support POST method?
formSave, ok := formSpec.(FormSpecSave)
if !ok {
RespondNotImplemented(w)
return
}
// CSRF protection
if !IsCSRFtokenValid(r, csrf) {
Log.DebugR(r, "CSRF token mismatch")
RespondBadRequest(w)
return
}
// initialize (empty) form
items, err := formSave.Read("")
if err != nil {
handleFormError(w, r, "could not initialize form", err)
return
}
// integrate values form posted form data and validate
isValid := items.setValues(r.Form)
if isValid {
action, err := formSave.Save(id, items)
if err != nil {
Log.ErrorObjR(r, "could not save form item", err)
RespondInternalServerError(w)
return
}
if action.isFormError {
renderForm(w, r, formName, items, submitButton, action.message)
return
}
action.doCloseDialog = r.Form.Get("dialog") == "true"
action.redirect = r.Form.Get("ref")
handleResponseAction(w, r, action)
return
}
renderForm(w, r, formName, items, submitButton, "")
case http.MethodDelete:
// does the form support DELETE method?
formDelete, ok := formSpec.(FormSpecDelete)
if !ok {
RespondNotImplemented(w)
return
}
// CSRF protection
if !IsCSRFtokenValid(r, csrf) {
Log.DebugR(r, "CSRF token mismatch")
RespondBadRequest(w)
return
}
action, err := formDelete.Delete(id)
if err != nil {
handleFormError(w, r, "could not delete form item", err)
return
}
action.doCloseDialog = r.Form.Get("dialog") == "true"
handleResponseAction(w, r, action)
default:
RespondNotImplemented(w)
}
}
}
func handleFormError(w http.ResponseWriter, r *http.Request, message string, err error) {
switch err {
case ErrorFormItemNotFound:
RespondNotFound(w)
return
case ErrorFormInvalidRequest:
RespondBadRequest(w)
return
}
// all other cases: log error and respond
Log.ErrorObjR(r, message, err)
RespondInternalServerError(w)
}
func renderForm(w http.ResponseWriter, r *http.Request, name string, form FormItems, submitButton, errorMessage string) {
// initialize form context
context := struct {
ID string
Items FormItems
Button string
Error string
}{name, form, submitButton, errorMessage}
err := renderInternalTemplate(w, r, "form", context)
if err != nil {
Log.ErrorContextR(
r, "could not render form",
LogContext{"name": name, "error": err},
)
RespondInternalServerError(w)
}
}