net/http
A handler is a function. A server without timeouts is unsafe to run, even if it is a teaching server.
A handler implements http.Handler or is adapted from a function through http.HandlerFunc. The function signature:
func health(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusOK)
}
The status code is written before the body. The first Write will send 200 itself if the status has not been set yet. After that the status cannot be changed: the headers have already left.
http.Server needs time limits. ReadHeaderTimeout protects against a client that opened a connection and stays silent. ReadTimeout and WriteTimeout limit a slow body. IdleTimeout closes idle keep-alive. A server without these fields accepts connections however it happens. This platform sets timeouts in main too. That is not decoration. It is part of the server.
A client http.Get without a context cannot be canceled. For outgoing requests take http.NewRequestWithContext and a client with Timeout, otherwise someone else's service will hang a goroutine.
Since Go 1.22 routes can be written on the standard ServeMux: method and path, GET /api/health, parameters {id}. A separate router is needed when the standard one is not enough. Do not drag in a framework while the mux is coping.
A handler error is turned into a status at the boundary. Do not give the client err.Error() from the database: schema details can be in there. Outward goes a short code and safe text. Into the journal goes the full chain.
Practice
When to write the status
The handler has already called
w.Write([]byte("ok"))without writing a status. What happens ifWriteHeader(500)is called next?- The client will see 500 and the body ok
- The status stays 200. It is too late to change it
- The server drops the connection with a panic
- WriteHeader cancels the bytes already written
A status class
Write
StatusClass(code int) string. Codes 200–299 aresuccess, 400–499 areclient, 500–599 areserver. Everything else isother.Server timeouts
Mark the fields of
http.Serverthat are worth setting on an ordinary service.- ReadHeaderTimeout
- ReadTimeout
- WriteTimeout
- Leave the zeros. The defaults are already strict