Movatterモバイル変換


[0]ホーム

URL:


httptest

packagestandard library
go1.25.2Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Oct 7, 2025 License:BSD-3-ClauseImports:19Imported by:17,438

Details

Repository

cs.opensource.google/go/go

Links

Documentation

Overview

Package httptest provides utilities for HTTP testing.

Index

Examples

Constants

View Source
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

funcNewRequestadded ingo1.7

func NewRequest(method, targetstring, bodyio.Reader) *http.Request

NewRequest wraps NewRequestWithContext using context.Background.

funcNewRequestWithContextadded ingo1.23.0

func NewRequestWithContext(ctxcontext.Context, method, targetstring, bodyio.Reader) *http.Request

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)Resultadded 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)WriteStringadded 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

func NewServer(handlerhttp.Handler) *Server

NewServer starts and returns a newServer.The caller should call Close when finished, to shut it down.

funcNewTLSServer

func NewTLSServer(handlerhttp.Handler) *Server

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

func NewUnstartedServer(handlerhttp.Handler) *Server

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)Certificateadded 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)Clientadded ingo1.9

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 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.

func (*Server)Start

func (s *Server) Start()

Start starts a server from NewUnstartedServer.

func (*Server)StartTLS

func (s *Server) StartTLS()

StartTLS starts TLS on a server from NewUnstartedServer.

Source Files

View all Source files

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f orF : Jump to
y orY : Canonical URL
go.dev uses cookies from Google to deliver and enhance the quality of its services and to analyze traffic.Learn more.

[8]ページ先頭

©2009-2025 Movatter.jp