httptest
packagestandard libraryThis package is not in the latest version of its module.
Details
Validgo.mod file
The Go module system was introduced in Go 1.11 and is the official dependency management solution for Go.
Redistributable license
Redistributable licenses place minimal restrictions on how software can be used, modified, and redistributed.
Tagged version
Modules with tagged versions give importers more predictable builds.
Stable version
When a project reaches major version v1 it is considered stable.
- Learn more about best practices
Repository
Links
Documentation¶
Overview¶
Package httptest provides utilities for HTTP testing.
Index¶
- Constants
- func NewRequest(method, target string, body io.Reader) *http.Request
- func NewRequestWithContext(ctx context.Context, method, target string, body io.Reader) *http.Request
- type ResponseRecorder
- func (rw *ResponseRecorder) Flush()
- func (rw *ResponseRecorder) Header() http.Header
- func (rw *ResponseRecorder) Result() *http.Response
- func (rw *ResponseRecorder) Write(buf []byte) (int, error)
- func (rw *ResponseRecorder) WriteHeader(code int)
- func (rw *ResponseRecorder) WriteString(str string) (int, error)
- type Server
Examples¶
Constants¶
const DefaultRemoteAddr = "1.2.3.4"
DefaultRemoteAddr is the default remote address to return in RemoteAddr ifan explicit DefaultRemoteAddr isn't set onResponseRecorder.
Variables¶
This section is empty.
Functions¶
funcNewRequest¶added ingo1.7
NewRequest wraps NewRequestWithContext using context.Background.
funcNewRequestWithContext¶added ingo1.23.0
NewRequestWithContext returns a new incoming server Request, suitablefor passing to anhttp.Handler for testing.
The target is theRFC 7230 "request-target": it may be either apath or an absolute URL. If target is an absolute URL, the host namefrom 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 typebytes.Reader,strings.Reader,bytes.Buffer, or the valuehttp.NoBody,the Request.ContentLength is set.
NewRequest panics on error for ease of use in testing, where apanic is acceptable.
To generate a client HTTP request instead of a server request, seethe NewRequest function in the net/http package.
Types¶
typeResponseRecorder¶
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.Codeint// 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.HeaderMaphttp.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.Flushedbool// contains filtered or unexported fields}
ResponseRecorder is an implementation ofhttp.ResponseWriter thatrecords its mutations for later inspection in tests.
Example¶
package mainimport ("fmt""io""net/http""net/http/httptest")func main() {handler := func(w http.ResponseWriter, r *http.Request) {io.WriteString(w, "<html><body>Hello World!</body></html>")}req := httptest.NewRequest("GET", "http://example.com/foo", nil)w := httptest.NewRecorder()handler(w, req)resp := w.Result()body, _ := io.ReadAll(resp.Body)fmt.Println(resp.StatusCode)fmt.Println(resp.Header.Get("Content-Type"))fmt.Println(string(body))}
Output:200text/html; charset=utf-8<html><body>Hello World!</body></html>
funcNewRecorder¶
func NewRecorder() *ResponseRecorder
NewRecorder returns an initializedResponseRecorder.
func (*ResponseRecorder)Flush¶
func (rw *ResponseRecorder) Flush()
Flush implementshttp.Flusher. To test whether Flush wascalled, see rw.Flushed.
func (*ResponseRecorder)Header¶
func (rw *ResponseRecorder) Header()http.Header
Header implementshttp.ResponseWriter. It returns the responseheaders to mutate within a handler. To test the headers that werewritten after a handler completes, use theResponseRecorder.Result method and seethe returned Response value's Header.
func (*ResponseRecorder)Result¶added ingo1.7
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 shouldnot DeepEqual the result in tests.
The Response.Header is a snapshot of the headers at the time of thefirst write call, or at the time of this call, if the handler neverdid a write.
The Response.Body is guaranteed to be non-nil and Body.Read call isguaranteed to not return any error other thanio.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 torw.Body, if not nil.
func (*ResponseRecorder)WriteHeader¶
func (rw *ResponseRecorder) WriteHeader(codeint)
WriteHeader implementshttp.ResponseWriter.
func (*ResponseRecorder)WriteString¶added ingo1.6
func (rw *ResponseRecorder) WriteString(strstring) (int,error)
WriteString implementsio.StringWriter. The data in str is writtento rw.Body, if not nil.
typeServer¶
type Server struct {URLstring// base URL of formhttp://ipaddr:port with no trailing slashListenernet.Listener// EnableHTTP2 controls whether HTTP/2 is enabled// on the server. It must be set between calling// NewUnstartedServer and calling Server.StartTLS.EnableHTTP2bool// 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 after calling NewUnstartedServer and// before Start or StartTLS.Config *http.Server// contains filtered or unexported fields}
A Server is an HTTP server listening on a system-chosen port on thelocal loopback interface, for use in end-to-end HTTP tests.
Example¶
package mainimport ("fmt""io""log""net/http""net/http/httptest")func main() {ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {fmt.Fprintln(w, "Hello, client")}))defer ts.Close()res, err := http.Get(ts.URL)if err != nil {log.Fatal(err)}greeting, err := io.ReadAll(res.Body)res.Body.Close()if err != nil {log.Fatal(err)}fmt.Printf("%s", greeting)}
Output:Hello, client
Example (HTTP2)¶
package mainimport ("fmt""io""log""net/http""net/http/httptest")func main() {ts := httptest.NewUnstartedServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {fmt.Fprintf(w, "Hello, %s", r.Proto)}))ts.EnableHTTP2 = truets.StartTLS()defer ts.Close()res, err := ts.Client().Get(ts.URL)if err != nil {log.Fatal(err)}greeting, err := io.ReadAll(res.Body)res.Body.Close()if err != nil {log.Fatal(err)}fmt.Printf("%s", greeting)}
Output:Hello, HTTP/2.0
funcNewServer¶
NewServer starts and returns a newServer.The caller should call Close when finished, to shut it down.
funcNewTLSServer¶
NewTLSServer starts and returns a newServer using TLS.The caller should call Close when finished, to shut it down.
Example¶
package mainimport ("fmt""io""log""net/http""net/http/httptest")func main() {ts := httptest.NewTLSServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {fmt.Fprintln(w, "Hello, client")}))defer ts.Close()client := ts.Client()res, err := client.Get(ts.URL)if err != nil {log.Fatal(err)}greeting, err := io.ReadAll(res.Body)res.Body.Close()if err != nil {log.Fatal(err)}fmt.Printf("%s", greeting)}
Output:Hello, client
funcNewUnstartedServer¶
NewUnstartedServer returns a newServer but doesn't start it.
After changing its configuration, the caller should call Start orStartTLS.
The caller should call Close when finished, to shut it down.
func (*Server)Certificate¶added ingo1.9
func (s *Server) Certificate() *x509.Certificate
Certificate returns the certificate used by the server, or nil ifthe server doesn't use TLS.
func (*Server)Client¶added ingo1.9
Client returns an HTTP client configured for making requests to the server.It is configured to trust the server's TLS test certificate and willclose its idle connections onServer.Close.Use Server.URL as the base URL to send requests to the server.
func (*Server)Close¶
func (s *Server) Close()
Close shuts down the server and blocks until all outstandingrequests on this server have completed.
func (*Server)CloseClientConnections¶
func (s *Server) CloseClientConnections()
CloseClientConnections closes any open HTTP connections to the test Server.