A simple way to handle form submissions from static websites.
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

69 lines
1.6 KiB

4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
  1. package main
  2. import (
  3. "github.com/microcosm-cc/bluemonday"
  4. "html"
  5. "net/http"
  6. "net/url"
  7. )
  8. type FormValues map[string][]string
  9. func FormHandler(w http.ResponseWriter, r *http.Request) {
  10. if r.Method == http.MethodGet {
  11. _, _ = w.Write([]byte("MailyGo works!"))
  12. return
  13. }
  14. if r.Method != http.MethodPost {
  15. w.WriteHeader(http.StatusMethodNotAllowed)
  16. _, _ = w.Write([]byte("The HTTP method is not allowed, make a POST request"))
  17. return
  18. }
  19. _ = r.ParseForm()
  20. sanitizedForm := sanitizeForm(r.PostForm)
  21. go func() {
  22. if !isBot(sanitizedForm) {
  23. sendForm(sanitizedForm)
  24. }
  25. }()
  26. sendResponse(sanitizedForm, w)
  27. return
  28. }
  29. func sanitizeForm(values url.Values) FormValues {
  30. p := bluemonday.StrictPolicy()
  31. sanitizedForm := make(FormValues)
  32. for key, values := range values {
  33. var sanitizedValues []string
  34. for _, value := range values {
  35. sanitizedValues = append(sanitizedValues, html.UnescapeString(p.Sanitize(value)))
  36. }
  37. sanitizedForm[html.UnescapeString(p.Sanitize(key))] = sanitizedValues
  38. }
  39. return sanitizedForm
  40. }
  41. func isBot(values FormValues) bool {
  42. for _, honeyPot := range appConfig.HoneyPots {
  43. if len(values[honeyPot]) > 0 {
  44. for _, value := range values[honeyPot] {
  45. if value != "" {
  46. return true
  47. }
  48. }
  49. }
  50. }
  51. return false
  52. }
  53. func sendResponse(values FormValues, w http.ResponseWriter) {
  54. if len(values["_redirectTo"]) == 1 && values["_redirectTo"][0] != "" {
  55. w.Header().Add("Location", values["_redirectTo"][0])
  56. w.WriteHeader(http.StatusSeeOther)
  57. _, _ = w.Write([]byte("Go to " + values["_redirectTo"][0]))
  58. return
  59. } else {
  60. w.WriteHeader(http.StatusCreated)
  61. _, _ = w.Write([]byte("Submitted form"))
  62. return
  63. }
  64. }