// Package web is the HTTP side of the notes app: a page for people and a JSON // list for programs. It gets everything it needs through New, and has no // package-level variables. package web import ( "bytes" "embed" "encoding/json" "html/template" "log/slog" "net/http" "time" "notes/internal/note" ) // templateFiles holds the template inside the program. // //go:embed templates/home.html var templateFiles embed.FS // Store is what the web side needs from a store. store.File has these // methods, and so does the memory store in the tests. type Store interface { All() []note.Note Add(n note.Note) (note.Note, error) } // App holds what the handlers need. Make one with New. type App struct { store Store logger *slog.Logger version string page *template.Template } // New reads the embedded template and returns an App that uses this store and // logger. The version is shown at the bottom of the page. func New(store Store, logger *slog.Logger, version string) (*App, error) { page, err := template.ParseFS(templateFiles, "templates/home.html") if err != nil { return nil, err } return &App{store: store, logger: logger, version: version, page: page}, nil } // Handler returns every route, wrapped so that each request is logged. func (a *App) Handler() http.Handler { mux := http.NewServeMux() mux.HandleFunc("GET /{$}", a.handleHome) mux.HandleFunc("POST /notes", a.handleAdd) mux.HandleFunc("GET /api/notes", a.handleList) return a.logRequests(mux) } type homeData struct { Error string Notes []note.Note Version string } // showHome builds the page in memory, and sends it only if that worked. func (a *App) showHome(w http.ResponseWriter, status int, message string) { data := homeData{Error: message, Notes: a.store.All(), Version: a.version} var page bytes.Buffer err := a.page.ExecuteTemplate(&page, "home.html", data) if err != nil { a.logger.Error("template failed", "err", err) http.Error(w, "The page could not be built.", http.StatusInternalServerError) return } w.Header().Set("Content-Type", "text/html; charset=utf-8") w.WriteHeader(status) page.WriteTo(w) } func (a *App) handleHome(w http.ResponseWriter, r *http.Request) { a.showHome(w, http.StatusOK, "") } func (a *App) handleAdd(w http.ResponseWriter, r *http.Request) { n, err := note.New(r.FormValue("text"), time.Now()) if err != nil { a.showHome(w, http.StatusBadRequest, err.Error()) return } added, err := a.store.Add(n) if err != nil { a.logger.Error("save failed", "err", err) http.Error(w, "The note could not be saved.", http.StatusInternalServerError) return } a.logger.Info("note added", "id", added.ID) http.Redirect(w, r, "/", http.StatusSeeOther) } func (a *App) handleList(w http.ResponseWriter, r *http.Request) { data, err := json.Marshal(a.store.All()) if err != nil { a.logger.Error("JSON failed", "err", err) http.Error(w, "The reply could not be built.", http.StatusInternalServerError) return } w.Header().Set("Content-Type", "application/json") w.Write(data) } // logRequests wraps a handler, and logs every request after it is answered. func (a *App) logRequests(next http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { start := time.Now() next.ServeHTTP(w, r) a.logger.Debug("request", "method", r.Method, "path", r.URL.Path, "took", time.Since(start)) }) }