-
Notifications
You must be signed in to change notification settings - Fork 0
/
forms.go
75 lines (67 loc) · 1.79 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
package main
import (
"html"
"net/http"
"net/url"
"github.com/microcosm-cc/bluemonday"
)
type FormValues map[string][]string
func FormHandler(w http.ResponseWriter, r *http.Request) {
if r.Method == http.MethodGet {
_, _ = w.Write([]byte("MailyGo works!"))
return
}
if r.Method != http.MethodPost {
w.WriteHeader(http.StatusMethodNotAllowed)
_, _ = w.Write([]byte("The HTTP method is not allowed, make a POST request"))
return
}
_ = r.ParseForm()
sanitizedForm := sanitizeForm(&r.PostForm)
go func() {
if !isBot(sanitizedForm) {
sendForm(sanitizedForm)
}
}()
sendResponse(sanitizedForm, w)
return
}
func sanitizeForm(values *url.Values) *FormValues {
p := bluemonday.StrictPolicy()
sanitizedForm := make(FormValues)
for key, values := range *values {
var sanitizedValues []string
for _, value := range values {
sanitizedValues = append(sanitizedValues, html.UnescapeString(p.Sanitize(value)))
}
sanitizedForm[html.UnescapeString(p.Sanitize(key))] = sanitizedValues
}
return &sanitizedForm
}
func isBot(values *FormValues) bool {
for _, honeyPot := range appConfig.HoneyPots {
if len((*values)[honeyPot]) > 0 {
for _, value := range (*values)[honeyPot] {
if value != "" {
return true
}
}
}
}
if len((*values)["_replyTo"]) == 0 || len((*values)["_replyTo"]) == 1 && (*values)["_replyTo"][0] == "" {
return true
}
return checkValues(values)
}
func sendResponse(values *FormValues, w http.ResponseWriter) {
if len((*values)["_redirectTo"]) == 1 && (*values)["_redirectTo"][0] != "" {
w.Header().Add("Location", (*values)["_redirectTo"][0])
w.WriteHeader(http.StatusSeeOther)
_, _ = w.Write([]byte("Go to " + (*values)["_redirectTo"][0]))
return
} else {
w.WriteHeader(http.StatusCreated)
_, _ = w.Write([]byte("Submitted form"))
return
}
}