123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081 |
- package main
- import (
- "errors"
- "html/template"
- "log"
- "net/http"
- "github.com/masterminds/sprig"
- )
- const (
- addr = ":8080"
- )
- type data map[string]any
- /*
- @app.route("/")
- def index():
- */
- func index(w http.ResponseWriter, r *http.Request) {
- http.Redirect(w, r, "/contacts", http.StatusSeeOther)
- }
- /*
- @app.route("/contacts")
- */
- func contacts(cs *ContactsStore) http.HandlerFunc {
- tpl := makeTemplate(
- "layout",
- "index",
- )
- return func(w http.ResponseWriter, r *http.Request) {
- search := r.URL.Query().Get("q")
- var contacts_set []Contact
- if search != "" {
- contacts_set = cs.GetAll()
- } else {
- contacts_set = cs.Get(search)
- }
- if err := tpl.ExecuteTemplate(w, "layout.html", data{
- "contacts": contacts_set,
- }); err != nil {
- http.Error(w, err.Error(), http.StatusInternalServerError)
- }
- }
- }
- func makeTemplate(first string, others ...string) *template.Template {
- paths := append([]string{first}, others...)
- for i, path := range paths {
- paths[i] = "./templates/" + path + ".gohtml"
- }
- tpl := template.Must(template.ParseFiles(paths...)).
- Funcs(sprig.FuncMap())
- return tpl
- }
- func setupRoutes(mux *http.ServeMux, cs *ContactsStore) {
- mux.HandleFunc("/", index)
- mux.Handle("/static/", http.StripPrefix("/static/", http.FileServer(http.Dir("./static"))))
- mux.Handle("/contacts", contacts(cs))
- }
- func main() {
- cs, err := NewContactsStore()
- if err != nil {
- log.Fatalf("initializing contacts: %v\n", err)
- }
- mux := http.NewServeMux()
- setupRoutes(mux, cs)
- log.Printf("Listening on http://localhost%s", addr)
- if err := http.ListenAndServe(addr, mux); err != nil {
- if !errors.Is(err, http.ErrServerClosed) {
- log.Printf("Server error: %v\n", err)
- return
- }
- }
- log.Println("Server shutdown")
- }
|