app.go 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. package main
  2. import (
  3. "errors"
  4. "html/template"
  5. "log"
  6. "net/http"
  7. "github.com/masterminds/sprig"
  8. )
  9. const (
  10. addr = ":8080"
  11. )
  12. type data map[string]any
  13. /*
  14. @app.route("/")
  15. def index():
  16. */
  17. func index(w http.ResponseWriter, r *http.Request) {
  18. http.Redirect(w, r, "/contacts", http.StatusSeeOther)
  19. }
  20. /*
  21. @app.route("/contacts")
  22. */
  23. func contacts(cs *ContactsStore) http.HandlerFunc {
  24. tpl := makeTemplate(
  25. "layout",
  26. "index",
  27. )
  28. return func(w http.ResponseWriter, r *http.Request) {
  29. search := r.URL.Query().Get("q")
  30. var contacts_set []Contact
  31. if search != "" {
  32. contacts_set = cs.GetAll()
  33. } else {
  34. contacts_set = cs.Get(search)
  35. }
  36. if err := tpl.ExecuteTemplate(w, "layout.html", data{
  37. "contacts": contacts_set,
  38. }); err != nil {
  39. http.Error(w, err.Error(), http.StatusInternalServerError)
  40. }
  41. }
  42. }
  43. func makeTemplate(first string, others ...string) *template.Template {
  44. paths := append([]string{first}, others...)
  45. for i, path := range paths {
  46. paths[i] = "./templates/" + path + ".gohtml"
  47. }
  48. tpl := template.Must(template.ParseFiles(paths...)).
  49. Funcs(sprig.FuncMap())
  50. return tpl
  51. }
  52. func setupRoutes(mux *http.ServeMux, cs *ContactsStore) {
  53. mux.HandleFunc("/", index)
  54. mux.Handle("/static/", http.StripPrefix("/static/", http.FileServer(http.Dir("./static"))))
  55. mux.Handle("/contacts", contacts(cs))
  56. }
  57. func main() {
  58. cs, err := NewContactsStore()
  59. if err != nil {
  60. log.Fatalf("initializing contacts: %v\n", err)
  61. }
  62. mux := http.NewServeMux()
  63. setupRoutes(mux, cs)
  64. log.Printf("Listening on http://localhost%s", addr)
  65. if err := http.ListenAndServe(addr, mux); err != nil {
  66. if !errors.Is(err, http.ErrServerClosed) {
  67. log.Printf("Server error: %v\n", err)
  68. return
  69. }
  70. }
  71. log.Println("Server shutdown")
  72. }