Capstone 3: the handlers
A handler in this service does four things: read the input, call the store, turn an error into a status and write a JSON answer. The input is the path value or the body, the store returns a note or a sentinel, and the writer helpers keep the content type and the error shape in one place. Every handler is under thirty lines.
Reading
list returns the array and a 200. get parses the id, calls the store and answers 200, 404 for the sentinel, 400 for an id that is not a number and 500 for anything else. The health route is a JSON {"status":"ok"} that a load balancer and a test both check.
package api
import (
"encoding/json"
"errors"
"net/http"
"strconv"
"example.com/notesapi/internal/store"
)
func (a *API) health(w http.ResponseWriter, r *http.Request) {
writeJSON(w, http.StatusOK, map[string]string{"status": "ok"})
}
func (a *API) list(w http.ResponseWriter, r *http.Request) {
notes, err := a.store.List()
if err != nil {
writeError(w, http.StatusInternalServerError, "cannot list notes")
return
}
writeJSON(w, http.StatusOK, notes)
}
type noteInput struct {
Title string `json:"title"`
Done bool `json:"done"`
}
func (a *API) create(w http.ResponseWriter, r *http.Request) {
var in noteInput
dec := json.NewDecoder(http.MaxBytesReader(w, r.Body, 1<<20))
dec.DisallowUnknownFields()
if err := dec.Decode(&in); err != nil {
writeError(w, http.StatusBadRequest, "invalid JSON body")
return
}
note, err := a.store.Create(in.Title)
if err != nil {
if errors.Is(err, store.ErrEmptyTitle) {
writeError(w, http.StatusBadRequest, err.Error())
return
}
writeError(w, http.StatusInternalServerError, "cannot create note")
return
}
writeJSON(w, http.StatusCreated, note)
}
func (a *API) get(w http.ResponseWriter, r *http.Request) {
id, err := strconv.Atoi(r.PathValue("id"))
if err != nil {
writeError(w, http.StatusBadRequest, "id must be a number")
return
}
note, err := a.store.Get(id)
if err != nil {
if errors.Is(err, store.ErrNotFound) {
writeError(w, http.StatusNotFound, "note not found")
return
}
writeError(w, http.StatusInternalServerError, "cannot read note")
return
}
writeJSON(w, http.StatusOK, note)
}
The two writers are the whole of the response contract. writeJSON sets the content type, the status and encodes, in that order; writeError does the same with the error shape. A handler that calls them cannot forget the header, which is the class of bug this helper exists to prevent.
package api
import (
"encoding/json"
"net/http"
)
type errorBody struct {
Error string `json:"error"`
}
// writeError answers with the shared error shape and the given status.
func writeError(w http.ResponseWriter, status int, msg string) {
w.Header().Set("Content-Type", "application/json; charset=utf-8")
w.WriteHeader(status)
json.NewEncoder(w).Encode(errorBody{Error: msg})
}
// writeJSON answers with a status and a JSON body.
func writeJSON(w http.ResponseWriter, status int, value any) {
w.Header().Set("Content-Type", "application/json; charset=utf-8")
w.WriteHeader(status)
json.NewEncoder(w).Encode(value)
}
A nil error and a non-nil one are the only two cases a handler branches on; the sentinel decides between 404 and 400, and everything else is a 500. The log line for the 500 belongs to the middleware, which does not know the error but does know the status.
Creating
The create is the handler with the most input: a body limited to a megabyte, a decoder that refuses an unknown field, a missing title and a bad document. The decoded input is a small struct, not the store type, so a client cannot set an id by sending one. The answer is 201 with the stored note.
func (a *API) update(w http.ResponseWriter, r *http.Request) {
id, err := strconv.Atoi(r.PathValue("id"))
if err != nil {
writeError(w, http.StatusBadRequest, "id must be a number")
return
}
var in noteInput
dec := json.NewDecoder(http.MaxBytesReader(w, r.Body, 1<<20))
dec.DisallowUnknownFields()
if err := dec.Decode(&in); err != nil {
writeError(w, http.StatusBadRequest, "invalid JSON body")
return
}
note, err := a.store.Update(id, in.Title, in.Done)
if err != nil {
switch {
case errors.Is(err, store.ErrNotFound):
writeError(w, http.StatusNotFound, "note not found")
case errors.Is(err, store.ErrEmptyTitle):
writeError(w, http.StatusBadRequest, err.Error())
default:
writeError(w, http.StatusInternalServerError, "cannot update note")
}
return
}
writeJSON(w, http.StatusOK, note)
}
func (a *API) delete(w http.ResponseWriter, r *http.Request) {
id, err := strconv.Atoi(r.PathValue("id"))
if err != nil {
writeError(w, http.StatusBadRequest, "id must be a number")
return
}
if err := a.store.Delete(id); err != nil {
if errors.Is(err, store.ErrNotFound) {
writeError(w, http.StatusNotFound, "note not found")
return
}
writeError(w, http.StatusInternalServerError, "cannot delete note")
return
}
w.WriteHeader(http.StatusNoContent)
}
The body limit is the one from lesson 104 and the strict decoder is the one from lesson 89. Both are one line and both turn a class of abuse into a 400 with a message instead of a slow handler. The update handler repeats the decode and maps the two sentinels to 404 and 400; the delete parses the id and answers 204.
Update and delete
An update is a full replacement of the title and the done flag, because the client has the note and sends it back. A patch would need a pointer per field to tell "not sent" from "set to zero", which this API does not need. The delete answers 204 and no body, and a delete of a missing id is 404, because a client that tries twice should learn the second time.
The error shape
Every error is an object with one key. The status and the message are the contract, and the middleware logs the request id next to them. A handler does not write a plain message: a client that parses every answer as JSON would break on the one error that is not.
The CRUD run
The demo creates a note, reads it, marks it done, asks for a missing id, sends an empty title and a broken document, deletes the note and reads it again. Every status is the one from the sections above.
package main
import (
"bytes"
"fmt"
"io"
"log/slog"
"net/http"
"net/http/httptest"
"example.com/notesapi/internal/api"
"example.com/notesapi/internal/store"
)
func main() {
a := api.New(store.NewMemory(), slog.New(slog.NewTextHandler(io.Discard, nil)))
srv := httptest.NewServer(a.Routes())
defer srv.Close()
call := func(method, path, body string) {
req, err := http.NewRequest(method, srv.URL+path, bytes.NewBufferString(body))
if err != nil {
panic(err)
}
if body != "" {
req.Header.Set("Content-Type", "application/json")
}
resp, err := http.DefaultClient.Do(req)
if err != nil {
panic(err)
}
data, _ := io.ReadAll(resp.Body)
resp.Body.Close()
fmt.Printf("%-6s %-14s %d %s", method, path, resp.StatusCode, data)
}
call("POST", "/api/notes", `{"title":"buy milk"}`)
call("GET", "/api/notes/1", "")
call("PUT", "/api/notes/1", `{"title":"buy milk","done":true}`)
call("GET", "/api/notes/9", "")
call("POST", "/api/notes", `{"title":""}`)
call("POST", "/api/notes", `{"title":`)
call("DELETE", "/api/notes/1", "")
call("GET", "/api/notes/1", "")
}
go run ./cmd/l131
POST /api/notes 201 {"id":1,"title":"buy milk","done":false}
GET /api/notes/1 200 {"id":1,"title":"buy milk","done":false}
PUT /api/notes/1 200 {"id":1,"title":"buy milk","done":true}
GET /api/notes/9 404 {"error":"note not found"}
POST /api/notes 400 {"error":"title is required"}
POST /api/notes 400 {"error":"invalid JSON body"}
DELETE /api/notes/1 204
GET /api/notes/1 404 {"error":"note not found"}
The delete answered with a status and no body, so the next line starts where the previous one ended in the output. The missing note after the delete is a 404, and the two 400s name the input problem. A client can branch on the status alone or show the error message, and the two agree.
A handler is small
The size of a handler is a design signal. This one parses, calls, maps and writes, and the rules live in the store and the writers. A handler that grows past a page is usually doing one of those four jobs twice. The next lesson moves the fifth job, the logging and the request id, into middleware around all of them.
Exercises
- Send a note with an extra field and read the status. Which decoder option makes it a 400, and what would a tolerant public API do instead?
- Send a body of two megabytes and read the response. Which status arrives, and which handler line produced it?
- Add a PATCH route with a pointer per field and decide what an omitted title means. Which handler grows, and what does the store method need?
Questions
A new set of questions in a new order every time. Choose one answer for each, then check.
-
What does a handler do?
Answer
Reads the input, calls the store, maps the error and writes JSON
The rules live elsewhere.
-
Which status is a missing note?
Answer
404
ErrNotFound maps to it.
-
Which status is a non-numeric id?
Answer
400
The client sent a bad path value.
-
What does writeJSON set first?
Answer
The content type, then the status, then the body
Headers after the status are ignored.
-
Why a separate input struct for create?
Answer
A client cannot set the id it does not own
The wire shape is not the model.
-
What does DisallowUnknownFields do here?
Answer
An extra key is a 400
The API is strict with its clients.
-
What does a delete answer?
Answer
204 with no body
The note is gone.
-
Why is update a full replacement?
Answer
The client has the note and sends it back
A patch is a different contract.
-
What is the error shape?
Answer
One object with an error key
Every route shares it.
-
Where does the 500 log line come from?
Answer
The middleware, which sees the status
The next lesson wires it.
The code on this page was run with go 1.26.10 on Alpine Linux 3.24.3 (x86_64) in a Docker container.
Article author: Arthur Isaev