Implement HTTP handlers and ResponseWriter
Implement HTTP handlers and ResponseWriter
A handler receives a request and writes its response. The http.Handler interface has one method, ServeHTTP(w, r); http.HandlerFunc adapts an ordinary function with that signature. The response writer is owned by the active request. Set headers before committing the final status, then write the body. The recorder below calls the handler directly without opening a socket.
package main
import ( "fmt" "net/http" "net/http/httptest" "strings")
func probe(h http.Handler, method, path, body string) *httptest.ResponseRecorder { w := httptest.NewRecorder() h.ServeHTTP(w, httptest.NewRequest(method, path, strings.NewReader(body))) return w}
type Health struct{}
func (Health) ServeHTTP(w http.ResponseWriter, r *http.Request) { w.Header().Set("Content-Type", "text/plain") fmt.Fprint(w, "ready")}func main() { w := probe(Health{}, "GET", "/health", "") fmt.Println(w.Result().StatusCode, w.Result().Header.Get("Content-Type"), w.Body.String())}Health satisfies the interface through its method. Fprint writes bytes and implicitly commits status 200 if no final status was sent. Result exposes the committed headers, rather than a mutable header map. The tiny in-memory examples omit write-error handling; on a real connection, a write can fail and must be handled according to the response contract.
Expected output:
200 text/plain readyCommit headers before the body
package main
import ( "fmt" "net/http" "net/http/httptest" "strings")
func probe(h http.Handler, method, path, body string) *httptest.ResponseRecorder { w := httptest.NewRecorder() h.ServeHTTP(w, httptest.NewRequest(method, path, strings.NewReader(body))) return w}func main() { h := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { w.Header().Set("X-Mode", "before") w.WriteHeader(http.StatusAccepted) w.Header().Set("X-Mode", "after") fmt.Fprint(w, "queued") }) w := probe(h, "POST", "/jobs", "") fmt.Println(w.Result().StatusCode, w.Result().Header.Get("X-Mode"), w.Body.String())}After a final status, changing ordinary headers does not change those sent to the client. A later error cannot replace the final status. Informational 1xx responses and trailers have distinct rules. Never retain w after ServeHTTP returns; requests can be handled concurrently.
Expected output:
202 before queuedTry it locally
Build a handler returning 201 and body created with Content-Type text/plain; print status, header and body.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
HTTP servers 01: Implement HTTP handlers and ResponseWriter
Check the lesson objective before moving on.
What does HandlerFunc adapt?
When must ordinary response headers be set?