HTTP status
An HTTP status code is the integer a handler sends with WriteHeader. The net/http package names the usual ones: StatusOK, StatusNotFound, StatusInternalServerError. The first write to the body implies 200 if you never called WriteHeader.
Detailed Explanation
Clients and proxies branch on the status. 2xx means success, 4xx means the client can fix the request, 5xx means the server failed. In Go you pass the constant, not a magic 404, so greps work: w.WriteHeader(http.StatusNotFound).
When the header is sent. WriteHeader sends it. Write sends 200 first if you have not. http.Error writes a status and a text body. After the header is gone, later WriteHeader calls are ignored (and since Go 1.20, http.Server can log a superfluous WriteHeader).
Common mapping.
| Situation | Code |
|---|---|
| JSON body OK | 200 |
| Created | 201 |
| No body | 204 |
| Bad JSON / validation | 400 |
| Auth missing | 401 |
| Auth present but forbidden | 403 |
| Unknown id | 404 |
| Wrong method | 405 |
| Conflict | 409 |
| Panic / unknown store error | 500 |
| Timeout / cancel | 499 (nonstandard) or 504 |
HEAD and GET. A GET handler should tolerate HEAD if the mux maps it there: write headers, skip the body, or let Server strip the body.
What it costs. Wrong statuses break retries and metrics. A store ErrNotFound that becomes 500 looks like an outage. Translate errors at the handler edge, once.
Code Examples
package main
import "net/http"
func get(w http.ResponseWriter, r *http.Request) {
if r.PathValue("id") == "" {
http.Error(w, "missing id", http.StatusBadRequest)
return
}
w.WriteHeader(http.StatusNoContent)
}
func main() {
http.HandleFunc("GET /items/{id}", get)
http.ListenAndServe(":8080", nil)
}func created(w http.ResponseWriter, loc string) {
w.Header().Set("Location", loc)
w.WriteHeader(http.StatusCreated)
}Common Gotchas
`Write` then `WriteHeader(404)` leaves a 200
set the status first.
`StatusNoContent` must not include a body
some clients fault if it does.
Constants live in `net/http`
prefer them over integers.
`http.Error` after you already wrote the body is too late
`http.Error` after you already wrote the body is too late