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.

67 lines
1.6 KiB

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. if !isBot(sanitizedForm) {
  22. sendForm(sanitizedForm)
  23. }
  24. sendResponse(sanitizedForm, w)
  25. return
  26. }
  27. func sanitizeForm(values url.Values) FormValues {
  28. p := bluemonday.StrictPolicy()
  29. sanitizedForm := make(FormValues)
  30. for key, values := range values {
  31. var sanitizedValues []string
  32. for _, value := range values {
  33. sanitizedValues = append(sanitizedValues, html.UnescapeString(p.Sanitize(value)))
  34. }
  35. sanitizedForm[html.UnescapeString(p.Sanitize(key))] = sanitizedValues
  36. }
  37. return sanitizedForm
  38. }
  39. func isBot(values FormValues) bool {
  40. for _, honeyPot := range appConfig.HoneyPots {
  41. if len(values[honeyPot]) > 0 {
  42. for _, value := range values[honeyPot] {
  43. if value != "" {
  44. return true
  45. }
  46. }
  47. }
  48. }
  49. return false
  50. }
  51. func sendResponse(values FormValues, w http.ResponseWriter) {
  52. if len(values["_redirectTo"]) == 1 && values["_redirectTo"][0] != "" {
  53. w.Header().Add("Location", values["_redirectTo"][0])
  54. w.WriteHeader(http.StatusSeeOther)
  55. _, _ = w.Write([]byte("Go to " + values["_redirectTo"][0]))
  56. return
  57. } else {
  58. w.WriteHeader(http.StatusCreated)
  59. _, _ = w.Write([]byte("Submitted form"))
  60. return
  61. }
  62. }