httptest

Imports

Imports #

"bytes"
"fmt"
"io"
"net/http"
"net/textproto"
"strconv"
"strings"
"golang.org/x/net/http/httpguts"
"crypto/tls"
"crypto/x509"
"flag"
"fmt"
"log"
"net"
"net/http"
"net/http/internal/testcert"
"os"
"strings"
"sync"
"time"
"bufio"
"bytes"
"context"
"crypto/tls"
"io"
"net/http"
"strings"

Constants & Variables

DefaultRemoteAddr const #

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"

serveFlag var #

When debugging a particular http server-based test, this flag lets you run go test -run='^BrokenTest$' -httptest.serve=127.0.0.1:8000 to start the broken server so you can interact with it manually. We only register this flag if it looks like the caller knows about it and is trying to use it as we don't want to pollute flags and this isn't really part of our API. Don't depend on this.

var serveFlag string

Interfaces

closeIdleTransport interface #

type closeIdleTransport interface {
CloseIdleConnections()
}

Structs

ResponseRecorder struct #

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

type ResponseRecorder struct {
Code int
HeaderMap http.Header
Body *bytes.Buffer
Flushed bool
result *http.Response
snapHeader http.Header
wroteHeader bool
}

Server struct #

A Server is an HTTP server listening on a system-chosen port on the local loopback interface, for use in end-to-end HTTP tests.

type Server struct {
URL string
Listener net.Listener
EnableHTTP2 bool
TLS *tls.Config
Config *http.Server
certificate *x509.Certificate
wg sync.WaitGroup
mu sync.Mutex
closed bool
conns map[net.Conn]http.ConnState
client *http.Client
}

Functions

Certificate method #

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

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

Client method #

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]. Use Server.URL as the base URL to send requests to the server.

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

Close method #

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

func (s *Server) Close()

CloseClientConnections method #

CloseClientConnections closes any open HTTP connections to the test Server.

func (s *Server) CloseClientConnections()

Flush method #

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

func (rw *ResponseRecorder) Flush()

NewRecorder function #

NewRecorder returns an initialized [ResponseRecorder].

func NewRecorder() *ResponseRecorder

NewRequest function #

NewRequest wraps NewRequestWithContext using context.Background.

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

NewRequestWithContext function #

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, or *bytes.Buffer, 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.

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

NewServer function #

NewServer starts and returns a new [Server]. The caller should call Close when finished, to shut it down.

func NewServer(handler http.Handler) *Server

NewTLSServer function #

NewTLSServer starts and returns a new [Server] using TLS. The caller should call Close when finished, to shut it down.

func NewTLSServer(handler http.Handler) *Server

NewUnstartedServer function #

NewUnstartedServer returns a new [Server] but doesn't start it. After changing its configuration, the caller should call Start or StartTLS. The caller should call Close when finished, to shut it down.

func NewUnstartedServer(handler http.Handler) *Server

Result method #

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 (rw *ResponseRecorder) Result() *http.Response

Start method #

Start starts a server from NewUnstartedServer.

func (s *Server) Start()

StartTLS method #

StartTLS starts TLS on a server from NewUnstartedServer.

func (s *Server) StartTLS()

Write method #

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

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

WriteHeader method #

WriteHeader implements [http.ResponseWriter].

func (rw *ResponseRecorder) WriteHeader(code int)

WriteString method #

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

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

checkWriteHeaderCode function #

func checkWriteHeaderCode(code int)

closeConn method #

closeConn closes c. s.mu must be held.

func (s *Server) closeConn(c net.Conn)

closeConnChan method #

closeConnChan is like closeConn, but takes an optional channel to receive a value when the goroutine closing c is done.

func (s *Server) closeConnChan(c net.Conn, done chan<- struct{...})

goServe method #

func (s *Server) goServe()

init function #

func init()

logCloseHangDebugInfo method #

func (s *Server) logCloseHangDebugInfo()

newLocalListener function #

func newLocalListener() net.Listener

parseContentLength function #

parseContentLength trims whitespace from s and returns -1 if no value is set, or the value if it's >= 0. This a modified version of same function found in net/http/transfer.go. This one just ignores an invalid header.

func parseContentLength(cl string) int64

strSliceContainsPrefix function #

func strSliceContainsPrefix(v []string, pre string) bool

wrap method #

wrap installs the connection state-tracking hook to know which connections are idle.

func (s *Server) wrap()

writeHeader method #

writeHeader writes a header if it was not written yet and detects Content-Type if needed. bytes or str are the beginning of the response body. We pass both to avoid unnecessarily generate garbage in rw.WriteString which was created for performance reasons. Non-nil bytes win.

func (rw *ResponseRecorder) writeHeader(b []byte, str string)

Generated with Arrow