Forms

This example will show how to simulate a contact form and parse the message into a struct.

  1. // forms.go
  2. package main
  3. import (
  4. "html/template"
  5. "net/http"
  6. )
  7. type ContactDetails struct {
  8. Email string
  9. Subject string
  10. Message string
  11. }
  12. func main() {
  13. tmpl := template.Must(template.ParseFiles("forms.html"))
  14. http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
  15. if r.Method != http.MethodPost {
  16. tmpl.Execute(w, nil)
  17. return
  18. }
  19. details := ContactDetails{
  20. Email: r.FormValue("email"),
  21. Subject: r.FormValue("subject"),
  22. Message: r.FormValue("message"),
  23. }
  24. // do something with details
  25. _ = details
  26. tmpl.Execute(w, struct{ Success bool }{true})
  27. })
  28. http.ListenAndServe(":8080", nil)
  29. }
  1. <!-- forms.html -->
  2. {{if .Success}}
  3. <h1>Thanks for your message!</h1>
  4. {{else}}
  5. <h1>Contact</h1>
  6. <form method="POST">
  7. <label>Email:</label><br />
  8. <input type="text" name="email"><br />
  9. <label>Subject:</label><br />
  10. <input type="text" name="subject"><br />
  11. <label>Message:</label><br />
  12. <textarea name="message"></textarea><br />
  13. <input type="submit">
  14. </form>
  15. {{end}}
  1. $ go run forms.go