net/http/httptest

net/http/httptest NewRequest, NewRecorder, and Result for in-memory handler tests, and why a Recorder is not a full server test.

The net/http/httptest package builds incoming requests and records a Handler’s writes in memory. Import it as "net/http/httptest". NewRequest produces a *http.Request suitable for ServeHTTP. NewRecorder is a ResponseWriter that stores the status, headers, and body. Result returns that data as a *http.Response after the handler has finished.

A Recorder is not a real server test. It does not listen, speak TLS, apply Server.ReadHeaderTimeout or other connection deadlines, run keep-alive, or perform HTTP/2 framing. Official documentation also says Result’s Response may gain fields in the future, so tests should not DeepEqual the whole value. For client-side tests without a network, use a fake RoundTripper on the client page rather than starting a listener.

These examples never call httptest.NewServer. Outputs were recorded with Go 1.24.0.

Examples were checked against Go 1.24.0. See the official package documentation for the complete API.

Go reference overview →

API index

APISummary
httptest.NewRequest, NewRecorder, and ResponseRecorder.ResultDrive a Handler in memory and read both the Recorder fields and the Result Response.
httptest.NewRequest inbound fieldsBuild an incoming GET with a host, path, query, and body, all in memory.

NewRecorder and Result

Call the Handler with ServeHTTP(rec, req), then read rec.Code, rec.Header, and rec.Body, or call rec.Result after the handler returns. Official documentation guarantees a non-nil Result body whose Read error is only io.EOF, and it requires that Result is used only after the handler has finished. Close that body when you are done, as you would close any other Response.Body.

httptest.NewRequest, NewRecorder, and ResponseRecorder.Result

func NewRequest(method, target string, body io.Reader) *http.Request
func NewRecorder() *ResponseRecorder
func (rw *ResponseRecorder) Result() *http.Response

Drive a Handler in memory and read both the Recorder fields and the Result Response.

ParameterDescription
method, target, bodyNewRequest arguments. target may be a full URL or a path. This constructor panics if the request cannot be built; it does not return an error.

Returns: NewRequest returns *http.Request. NewRecorder returns *ResponseRecorder. Result returns *http.Response with at least StatusCode, Header, and Body filled.

Errors

  • panic — NewRequest panics on an invalid target. Result itself does not report handler errors; the handler must write a status or body.
  • NewRequest wraps NewRequestWithContext using context.Background.
go
package main

import (
	"fmt"
	"io"
	"net/http"
	"net/http/httptest"
)

func main() {
	handler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		w.Header().Set("X-Test", "1")
		w.WriteHeader(http.StatusCreated)
		fmt.Fprint(w, "created:", r.URL.Path)
	})

	req := httptest.NewRequest(http.MethodPost, "https://example.test/items", nil)
	rec := httptest.NewRecorder()
	handler.ServeHTTP(rec, req)
	fmt.Println(rec.Code, rec.Header().Get("X-Test"), rec.Body.String())

	res := rec.Result()
	defer res.Body.Close()
	body, err := io.ReadAll(res.Body)
	fmt.Println(res.StatusCode, err, string(body))
}

Expected output

201 1 created:/items
201 <nil> created:/items

Related: net/http (server), net/http (client)

Official documentation →

Inbound request fields

httptest.NewRequest fills the fields a server Handler expects: Method, Host, URL, and Body among them. That is a different layout from an outbound client request built with http.NewRequest. The example reads those incoming fields and the body from memory. No timeout on a Server is applied, because the test never starts a Server.

httptest.NewRequest inbound fields

func NewRequest(method, target string, body io.Reader) *http.Request

Build an incoming GET with a host, path, query, and body, all in memory.

ParameterDescription
targetA URL used to fill Host, URL.Path, and URL.RawQuery. example.test is sample data and is not resolved.
bodyOptional request body. A strings.Reader is enough for a Handler test.

Returns: A *http.Request whose Context is non-nil (context.Background unless you use NewRequestWithContext).

  • Use this constructor for Handler tests. Use http.NewRequest or http.NewRequestWithContext for Client.Do, as official documentation distinguishes inbound and outbound fields.
go
package main

import (
	"fmt"
	"io"
	"net/http"
	"net/http/httptest"
	"strings"
)

func main() {
	req := httptest.NewRequest(http.MethodGet, "https://example.test/items?q=1", strings.NewReader("body"))
	fmt.Println(req.Method, req.Host, req.URL.Path, req.URL.RawQuery)
	b, err := io.ReadAll(req.Body)
	fmt.Println(err, string(b))
	fmt.Println(req.Context() != nil)
}

Expected output

GET example.test /items q=1
<nil> body
true

Related: context, net/url

Official documentation →