Web services
net/http routing, handlers, middleware, shutdown, and project layout.
What did Go 1.22 add that removed most of the reason to use a web framework?
All questions with explanations (answers shown)
1. What did Go 1.22 add that removed most of the reason to use a web framework?
Answer: Method and path-parameter routing:
mux.HandleFunc("GET /users/{id}", h)Before 1.22
ServeMuxmatched paths only, so you routed methods by hand. Nowr.PathValue("id")gets the parameter and the framework buys you very little.2. What is the correct order inside a handler?
Answer: Set headers, then
WriteHeader, then write the bodyHeaders set after
WriteHeaderare silently dropped, and writing a body impliesWriteHeader(200). Alwaysreturnright after writing an error, or you get "superfluous WriteHeader".3. What is wrong with
http.ListenAndServe(":8080", mux)in production?Answer: The zero-value server has no timeouts, so one slow client can hold a connection forever
Configure
http.ServerwithReadHeaderTimeout(the Slowloris defence),ReadTimeout,WriteTimeoutandIdleTimeout.4. What is a middleware in Go?
Answer: A function taking an
http.Handlerand returning anhttp.HandlerThat is the whole mechanism. You compose by nesting, so no framework is required.
5. Your recover middleware wraps every handler. A goroutine you started inside a handler panics. What happens?
Answer: It kills the whole process — a parent recover cannot catch it
Recover only works in the panicking goroutine’s own deferred function. Every long-lived goroutine you launch needs its own
defer recover().6. Why must
signal.Notify’s channel be buffered?Answer:
signal.Notifynever blocks, so an unbuffered channel with nobody receiving yet drops the signalmake(chan os.Signal, 1). Get this wrong and your graceful shutdown silently never triggers.7. A handler calls
w.Write(body)and thenw.WriteHeader(http.StatusCreated). What does the client get?Answer: 200 OK, and the server logs "superfluous response.WriteHeader call"
The first
Writesends a 200 if no status was set. After that the status is fixed, so the laterWriteHeaderonly produces a log line. CallWriteHeader(201)before writing the body.8. You start
srv := &http.Server{Addr: ":8080", Handler: mux}with no timeouts. Which one fix matters most?Answer: Set
ReadHeaderTimeout, so a client that sends headers very slowly cannot hold a connection open foreverWith no timeouts, a slow client (Slowloris) can keep many connections open by trickling headers.
ReadHeaderTimeoutcloses them. SetReadTimeout,WriteTimeoutandIdleTimeouttoo.