forked from jbrook/gforms
-
Notifications
You must be signed in to change notification settings - Fork 0
/
login_form.go
66 lines (62 loc) · 1.3 KB
/
login_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
package main
import (
"fmt"
"github.com/bluele/gforms"
"net/http"
"text/template"
)
type User struct {
Email string `gforms:"email"`
Password string `gforms:"password"`
}
var tplText string = `
<form method="post">
{{range $i, $field := .Fields}}
<label>{{$field.GetName}}: </label>{{$field.Html}}
{{range $ei, $err := $field.Errors}}
<label class="error">{{$err}}</label>
{{end}}
<br />
{{end}}
<input type="submit">
</form>
`
func main() {
tpl, _ := template.New("tpl").Parse(tplText)
loginForm := gforms.DefineForm(
gforms.NewFields(
gforms.NewTextField(
"email",
gforms.Validators{
gforms.Required(),
gforms.MinLengthValidator(4),
gforms.EmailValidator(),
},
),
gforms.NewTextField(
"password",
gforms.Validators{
gforms.Required(),
gforms.MinLengthValidator(4),
gforms.MaxLengthValidator(16),
},
gforms.PasswordInputWidget(map[string]string{}),
),
))
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "text/html")
form := loginForm(r)
if r.Method != "POST" {
tpl.Execute(w, form)
return
}
if !form.IsValid() {
tpl.Execute(w, form)
return
}
user := User{}
form.MapTo(&user)
fmt.Fprintf(w, "ok: %v", user)
})
http.ListenAndServe(":9000", nil)
}