package web // This is the starter. readMonth, handleList and handleGet are finished. The // TODOs are in handleCreate, handleDelete and handleReport. import ( "errors" "fmt" "net/http" "expenses/internal/expense" "expenses/internal/store" ) // maxBodyBytes is the largest request body the API reads. const maxBodyBytes = 4096 // expenseInput is what a client sends to create an expense. It has no ID, // because the store chooses the ID. type expenseInput struct { Date string `json:"date"` Category string `json:"category"` Note string `json:"note"` Cents int64 `json:"cents"` } // readMonth reads ?month= from the URL. An empty month means every month. On // failure it has already replied. func readMonth(w http.ResponseWriter, r *http.Request) (string, bool) { month := r.URL.Query().Get("month") if month == "" { return "", true } err := expense.CheckMonth(month) if err != nil { writeError(w, http.StatusBadRequest, err.Error()) return "", false } return month, true } // GET /api/expenses?month=2026-11 func (a *App) handleList(w http.ResponseWriter, r *http.Request) { month, ok := readMonth(w, r) if !ok { return } writeJSON(w, http.StatusOK, expense.InMonth(a.store.List(), month)) } // POST /api/expenses func (a *App) handleCreate(w http.ResponseWriter, r *http.Request) { // TODO: read the body into an expenseInput with readJSON. A // *http.MaxBytesError (find it with errors.As) gets status 413, and any // other error gets 400. Check the values with expense.New (400 if they are // wrong), and add the expense to a.store (500 if that fails, and log the // error). Log the new expense, set the Location header to // /api/expenses/{id}, and reply 201 with the expense that Add returned. writeError(w, http.StatusNotImplemented, "TODO: handleCreate is not written yet") } // GET /api/expenses/{id} func (a *App) handleGet(w http.ResponseWriter, r *http.Request) { id, ok := readID(w, r) if !ok { return } e, err := a.store.Get(id) if errors.Is(err, store.ErrNotFound) { writeError(w, http.StatusNotFound, fmt.Sprintf("no expense has the id %d", id)) return } if err != nil { a.logger.Error("could not read", "id", id, "err", err) writeError(w, http.StatusInternalServerError, "the expense could not be read") return } writeJSON(w, http.StatusOK, e) } // DELETE /api/expenses/{id} func (a *App) handleDelete(w http.ResponseWriter, r *http.Request) { // TODO: read the ID as handleGet does, and delete it from a.store. // store.ErrNotFound gets 404, and any other error 500. On success, log it // and reply 204 with no body. writeError(w, http.StatusNotImplemented, "TODO: handleDelete is not written yet") } // GET /api/report?month=2026-11 func (a *App) handleReport(w http.ResponseWriter, r *http.Request) { // TODO: read the month as handleList does, and reply 200 with // expense.Summarize of the expenses in that month. writeError(w, http.StatusNotImplemented, "TODO: handleReport is not written yet") }