Package httptest

import "net/http/httptest"
Overview
Index
Examples

Overview ▾

Package httptest provides utilities for HTTP testing.

Constants

DefaultRemoteAddr is the default remote address to return in RemoteAddr if an explicit DefaultRemoteAddr isn't set on ResponseRecorder.

const DefaultRemoteAddr = "1.2.3.4"

func NewRequest

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

NewRequest wraps NewRequestWithContext using context.Background.

func NewRequestWithContext

func NewRequestWithContext(ctx context.Context, method, target string, body io.Reader) *http.Request

NewRequestWithContext returns a new incoming server Request, suitable for passing to an http.Handler for testing.

The target is the RFC 7230 "request-target": it may be either a path or an absolute URL. If target is an absolute URL, the host name from the URL is used. Otherwise, "example.com" is used.

The TLS field is set to a non-nil dummy value if target has scheme "https".

The Request.Proto is always HTTP/1.1.

An empty method means "GET".

The provided body may be nil. If the body is of type bytes.Reader, strings.Reader, bytes.Buffer, or the value http.NoBody, the Request.ContentLength is set.

NewRequest panics on error for ease of use in testing, where a panic is acceptable.

To generate a client HTTP request instead of a server request, see the NewRequest function in the net/http package.

type ResponseRecorder

ResponseRecorder is an implementation of http.ResponseWriter that records its mutations for later inspection in tests.

type ResponseRecorder struct {
    // Code is the HTTP response code set by WriteHeader.
    //
    // Note that if a Handler never calls WriteHeader or Write,
    // this might end up being 0, rather than the implicit
    // http.StatusOK. To get the implicit value, use the Result
    // method.
    Code int

    // HeaderMap contains the headers explicitly set by the Handler.
    // It is an internal detail.
    //
    // Deprecated: HeaderMap exists for historical compatibility
    // and should not be used. To access the headers returned by a handler,
    // use the Response.Header map as returned by the Result method.
    HeaderMap http.Header

    // Body is the buffer to which the Handler's Write calls are sent.
    // If nil, the Writes are silently discarded.
    Body *bytes.Buffer

    // Flushed is whether the Handler called Flush.
    Flushed bool
    // contains filtered or unexported fields
}

Example

200
text/html; charset=utf-8
<html><body>Hello World!</body></html>

func NewRecorder

func NewRecorder() *ResponseRecorder

NewRecorder returns an initialized ResponseRecorder.

func (*ResponseRecorder) Flush

func (rw *ResponseRecorder) Flush()

Flush implements http.Flusher. To test whether Flush was called, see rw.Flushed.

func (*ResponseRecorder) Header

func (rw *ResponseRecorder) Header() http.Header

Header implements http.ResponseWriter. It returns the response headers to mutate within a handler. To test the headers that were written after a handler completes, use the ResponseRecorder.Result method and see the returned Response value's Header.

func (*ResponseRecorder) Result

func (rw *ResponseRecorder) Result() *http.Response

Result returns the response generated by the handler.

The returned Response will have at least its StatusCode, Header, Body, and optionally Trailer populated. More fields may be populated in the future, so callers should not DeepEqual the result in tests.

The Response.Header is a snapshot of the headers at the time of the first write call, or at the time of this call, if the handler never did a write.

The Response.Body is guaranteed to be non-nil and Body.Read call is guaranteed to not return any error other than io.EOF.

Result must only be called after the handler has finished running.

func (*ResponseRecorder) Write

func (rw *ResponseRecorder) Write(buf []byte) (int, error)

Write implements http.ResponseWriter. The data in buf is written to rw.Body, if not nil.

func (*ResponseRecorder) WriteHeader

func (rw *ResponseRecorder) WriteHeader(code int)

WriteHeader implements http.ResponseWriter.

func (*ResponseRecorder) WriteString

func (rw *ResponseRecorder) WriteString(str string) (int, error)

WriteString implements io.StringWriter. The data in str is written to rw.Body, if not nil.

type Server

A Server is an HTTP server for use in end-to-end HTTP tests.

Most tests should create a server with NewTestServer. The Server.Client method returns a client which sends requests to the test server.

// Create a test server and send a request to it.
server := httptest.NewTestServer(t, handler)
resp, err := server.Client().Get("http://www.example.com/")

Configuration

Tests may change a Server's configuration prior to using it. The configuration must not be changed after the first call to Server.Client, Server.Start, or Server.StartTLS.

// Configure a test server before using.
server := httptest.NewTestServer(t, handler)
server.Config.MaxHeaderBytes = 1024
resp, err := server.Client().Get("http://www.example.com/")

Tests

Servers created with NewTestServer will:

Servers created in any other way must be manually shut down with Server.Close.

In-Memory Network

A Server may use an in-memory network implementation or listen on a local network loopback interface. Most tests should use the in-memory network, which avoids port exhaustion and other transient networking issues and is suitable for use with the testing/synctest package.

To use the in-memory network, create a server with NewTestServer. Do not call Server.Start or Server.StartTLS.

When using the in-memory network, the http.Client returned by Server.Client is configured to send all requests to the server. The client will direct HTTP and HTTPS requests, regardless of destination address or hostname, to the server. Requests do not need to use [Server.URL] as the base URL.

server := httptest.NewTestServer(t, handler)
client := server.Client()

// All of these requests are sent to the test server.
// https:// requests use TLS over the in-memory network.
_, _ = client.Get("http://www.example.com/")
_, _ = client.Get("https://go.dev/")
_, _ = client.Get("http://10.0.0.1/")

The [Server.Listener] field is not set when using the in-memory network.

Loopback Network

To listen on a loopback interface, call Server.Start or Server.StartTLS. The server will listen on a system-chosen port.

Loopback servers serve one of HTTP (when started with Server.Start) or HTTPS (when started with Server.StartTLS).

When using the loopback network, the http.Client returned by Server.Client is configured to send requests with a hostname of "example.com" or a subdomain of ".example.com" to the server.

Requests may also be sent to the server's loopback address. The [Server.URL] field is set to a base URL containing the server's address.

server := httptest.NewTestServer(t, handler)
server.Start()
client := server.Client()

// This request is sent to the test server.
_, _ = server.Client().Get(server.URL + "/")

// This request (using http.DefaultClient) is also sent to the test server,
// since server.URL contains the server's local IP address.
_, _ = http.Get(server.URL + "/")
type Server struct {
    // URL is the base URL of the server, of the form http://address:port
    // with no trailing slash.
    //
    // It is set by the first call to Client, Start, or StartTLS.
    //
    // For servers listening on loopback, the address is the loopback IP address
    // of the server.
    //
    // For servers using the in-memory network, this address is "example.com".
    // Requests sent to servers using the in-memory network may use any address.
    // It is not necessary to use this base URL.
    URL string

    // Listener is the network listener for servers listening on loopback.
    // It is not set for servers using the in-memory network.
    Listener net.Listener

    // EnableHTTP2 controls whether HTTP/2 is enabled on the server.
    // It must be set before calling Client, Start, or StartTLS.
    EnableHTTP2 bool

    // TLS is the optional TLS configuration, populated with a new config
    // after TLS is started. If set on an unstarted server before StartTLS
    // is called, existing fields are copied into the new config.
    TLS *tls.Config

    // Config may be changed before calling Client, Start, or StartTLS.
    Config *http.Server
    // contains filtered or unexported fields
}

Example

Hello, client

Example (HTTP2)

Hello, HTTP/2.0

func NewServer

func NewServer(handler http.Handler) *Server

NewServer starts and returns a new Server listening on a local network loopback interface. This is equivalent to calling NewUnstartedServer followed by Server.Start.

The caller should call Server.Close when finished, to shut it down.

Most users should use NewTestServer instead. See the Server documentation for details.

func NewTLSServer

func NewTLSServer(handler http.Handler) *Server

NewTLSServer starts and returns a new Server using TLS and listening on a local network loopback interface. This is equivalent to calling NewUnstartedServer followed by Server.StartTLS.

The caller should call Server.Close when finished, to shut it down.

Most users should use NewTestServer instead. See the Server documentation for details.

Example

Hello, client

func NewTestServer

func NewTestServer(t testing.TB, handler http.Handler) *Server

NewTestServer returns a new Server for a test. The server will use an in-memory network implementation by default.

If the handler is nil, the server will serve 500 responses to all requests. It will not use http.DefaultServeMux.

See the Server documentation for more details.

func NewUnstartedServer

func NewUnstartedServer(handler http.Handler) *Server

NewUnstartedServer returns a new Server listening on a local network loopback interface. It does not start the server.

After changing the server's configuration, the caller should call Server.Start or Server.StartTLS.

The caller should call Server.Close when finished, to shut it down.

Most users should use NewTestServer instead. See the Server documentation for details.

func (*Server) Certificate

func (s *Server) Certificate() *x509.Certificate

Certificate returns the certificate used by the server, or nil if the server doesn't use TLS.

func (*Server) Client

func (s *Server) Client() *http.Client

Client returns an HTTP client configured for making requests to the server. It is configured to trust the server's TLS test certificate and will close its idle connections on Server.Close.

func (*Server) Close

func (s *Server) Close()

Close shuts down the server and blocks until all outstanding requests on this server have completed.

func (*Server) CloseClientConnections

func (s *Server) CloseClientConnections()

CloseClientConnections closes any open HTTP connections to the test Server.

func (*Server) Start

func (s *Server) Start()

Start starts a server on a local loopback network interface.

The server should have been created by NewTestServer or NewUnstartedServer.

func (*Server) StartTLS

func (s *Server) StartTLS()

Start starts TLS on a server on a local loopback network interface.

The server should have been created by NewTestServer or NewUnstartedServer.