// Package web is the HTTP side of the expense tracker: an HTML page with a form // for people, and a JSON API under /api/ for programs. It gets everything it // needs through New, and has no package-level variables. package web import ( "embed" "encoding/json" "errors" "html/template" "io" "log/slog" "net/http" "strconv" "time" "expenses/internal/expense" ) // templateFiles holds the template inside the program, so the .exe needs no // other files next to it. // //go:embed templates/home.html var templateFiles embed.FS // Store is what the web side needs from a store. The file store in package // store has these methods, and so does the memory store in the tests. type Store interface { List() []expense.Expense Get(id int) (expense.Expense, error) Add(e expense.Expense) (expense.Expense, error) Delete(id int) 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() // Pages for people. mux.HandleFunc("GET /{$}", a.handleHome) mux.HandleFunc("POST /expenses", a.handleAddForm) mux.HandleFunc("POST /expenses/{id}/delete", a.handleDeleteForm) // The JSON API for programs. mux.HandleFunc("GET /api/expenses", a.handleList) mux.HandleFunc("POST /api/expenses", a.handleCreate) mux.HandleFunc("GET /api/expenses/{id}", a.handleGet) mux.HandleFunc("DELETE /api/expenses/{id}", a.handleDelete) mux.HandleFunc("GET /api/report", a.handleReport) return a.logRequests(mux) } // statusRecorder is a ResponseWriter that remembers the status code. It embeds // the real one (Chapter 29), so every other method still works. type statusRecorder struct { http.ResponseWriter status int } func (r *statusRecorder) WriteHeader(status int) { r.status = status r.ResponseWriter.WriteHeader(status) } // logRequests logs one line for every request, after it is answered. The line // is at the debug level, so it shows only with -log-level debug. func (a *App) logRequests(next http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { start := time.Now() recorder := &statusRecorder{ResponseWriter: w, status: http.StatusOK} next.ServeHTTP(recorder, r) a.logger.Debug("request", "method", r.Method, "path", r.URL.Path, "status", recorder.status, "duration", time.Since(start)) }) } // errorReply is the body of every error response. type errorReply struct { Error string `json:"error"` } // writeJSON sends value as JSON with the given status. func writeJSON(w http.ResponseWriter, status int, value any) { data, err := json.MarshalIndent(value, "", " ") if err != nil { http.Error(w, "Internal Server Error", http.StatusInternalServerError) return } data = append(data, '\n') w.Header().Set("Content-Type", "application/json") w.WriteHeader(status) // An error here means the client has gone, so there is no one to tell. w.Write(data) } // writeError sends {"error": message} with the given status. func writeError(w http.ResponseWriter, status int, message string) { writeJSON(w, status, errorReply{Error: message}) } // readJSON decodes the request body into dst. It allows one JSON value of at // most maxBodyBytes, with no fields that dst does not have. func readJSON(w http.ResponseWriter, r *http.Request, dst any) error { r.Body = http.MaxBytesReader(w, r.Body, maxBodyBytes) decoder := json.NewDecoder(r.Body) decoder.DisallowUnknownFields() err := decoder.Decode(dst) if err != nil { return err } err = decoder.Decode(&struct{}{}) if !errors.Is(err, io.EOF) { return errors.New("the body must hold one JSON object only") } return nil } // readID reads the {id} part of the path. On failure it has already replied. func readID(w http.ResponseWriter, r *http.Request) (int, bool) { id, err := strconv.Atoi(r.PathValue("id")) if err != nil { writeError(w, http.StatusBadRequest, "the id must be a whole number") return 0, false } return id, true }