http
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusOK)
fmt.Fprintln(w, "local")
}))
defer server.Close()
resp, err := http.Get(server.URL)
defer resp.Body.Close()
That ran with no external network
httptest
It gives a real server on a local address Perfect for tests and labs No port collisions with a fixed listener
Handlers
ResponseWriter writes the response
Request carries the input
Set headers before writing the body, once the body starts headers are on the wire
Always close the body
defer resp.Body.Close() is required
Go 1.27 notes that HTTP/1 response bodies now drain unread content on close for better connection reuse
That makes cleanup more useful, not optional
Timeouts
Use a client with a timeout A default client can wait forever on a hostile server Timeouts are a correctness feature
Next
Modules and tools in 09 modules and tools
Posted