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.

66 lines
1.6 KiB

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