httptest is Go’s standard-library toolkit for exercising HTTP code with real net/http types in a controlled environment. It supports tests that go beyond mocked transport behavior: a client can send requests through TCP and HTTP layers to a test server, while handlers can receive constructed requests and write captured responses. section 7.6 section 8.8.2
Use httptest.Server when a test needs an HTTP server. NewServer accepts an http.Handler, starts a server configured for testing, and exposes its address through URL. Close the server when the test is finished to free resources. section 7.6.1
func NewServer( #1
handler http.Handler, #1
) *httptest.Server #1
NewServer takes the handler that will serve every request received by the test server. section 7.6.1
Build an HTTP server test in a direct sequence:
- Create a handler with http.HandlerFunc, converting a closure with the appropriate signature into an http.Handler. section 7.6.1
- Start the server with httptest.NewServer and direct the HTTP client to server.URL. section 7.6.1
- Run the client normally, then close the server after assertions and result processing finish. section 7.6 section 7.6.1
- For handler-focused tests, use NewRequest to supply a request and NewRecorder to capture the ResponseWriter output. section 8.8.2
Testing a client against a local server
A client that otherwise targets a remote endpoint can instead target server.URL. The test server invokes its configured handler for each incoming request, allowing the test to exercise request sending and response processing over the HTTP networking path rather than only replacing a RoundTripper. section 7.6 section 7.6.1
httptest favors real Request, Server, and ResponseWriter behavior instead of test-only mock types. This keeps tests closer to production behavior, while a server’s configurable handler makes it practical to isolate routes or responses under test. section 8.8.2



