summaryrefslogtreecommitdiff
path: root/devdocs/go/net%2Fhttp%2Fhttptest%2Findex.html
blob: 46304728887c0a59965a5b06c36111aaba80311a (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
<h1> Package httptest  </h1>     <ul id="short-nav">
<li><code>import "net/http/httptest"</code></li>
<li><a href="#pkg-overview" class="overviewLink">Overview</a></li>
<li><a href="#pkg-index" class="indexLink">Index</a></li>
<li><a href="#pkg-examples" class="examplesLink">Examples</a></li>
</ul>     <h2 id="pkg-overview">Overview </h2> <p>Package httptest provides utilities for HTTP testing. </p>     <h2 id="pkg-index">Index </h2>  <ul id="manual-nav">
<li><a href="#pkg-constants">Constants</a></li>
<li><a href="#NewRequest">func NewRequest(method, target string, body io.Reader) *http.Request</a></li>
<li><a href="#ResponseRecorder">type ResponseRecorder</a></li>
<li> <a href="#NewRecorder">func NewRecorder() *ResponseRecorder</a>
</li>
<li> <a href="#ResponseRecorder.Flush">func (rw *ResponseRecorder) Flush()</a>
</li>
<li> <a href="#ResponseRecorder.Header">func (rw *ResponseRecorder) Header() http.Header</a>
</li>
<li> <a href="#ResponseRecorder.Result">func (rw *ResponseRecorder) Result() *http.Response</a>
</li>
<li> <a href="#ResponseRecorder.Write">func (rw *ResponseRecorder) Write(buf []byte) (int, error)</a>
</li>
<li> <a href="#ResponseRecorder.WriteHeader">func (rw *ResponseRecorder) WriteHeader(code int)</a>
</li>
<li> <a href="#ResponseRecorder.WriteString">func (rw *ResponseRecorder) WriteString(str string) (int, error)</a>
</li>
<li><a href="#Server">type Server</a></li>
<li> <a href="#NewServer">func NewServer(handler http.Handler) *Server</a>
</li>
<li> <a href="#NewTLSServer">func NewTLSServer(handler http.Handler) *Server</a>
</li>
<li> <a href="#NewUnstartedServer">func NewUnstartedServer(handler http.Handler) *Server</a>
</li>
<li> <a href="#Server.Certificate">func (s *Server) Certificate() *x509.Certificate</a>
</li>
<li> <a href="#Server.Client">func (s *Server) Client() *http.Client</a>
</li>
<li> <a href="#Server.Close">func (s *Server) Close()</a>
</li>
<li> <a href="#Server.CloseClientConnections">func (s *Server) CloseClientConnections()</a>
</li>
<li> <a href="#Server.Start">func (s *Server) Start()</a>
</li>
<li> <a href="#Server.StartTLS">func (s *Server) StartTLS()</a>
</li>
</ul> <div id="pkg-examples"> <h3>Examples</h3>  <dl> <dd><a class="exampleLink" href="#example_NewTLSServer">NewTLSServer</a></dd> <dd><a class="exampleLink" href="#example_ResponseRecorder">ResponseRecorder</a></dd> <dd><a class="exampleLink" href="#example_Server">Server</a></dd> <dd><a class="exampleLink" href="#example_Server_hTTP2">Server (HTTP2)</a></dd> </dl> </div> <h3>Package files</h3> <p>  <span>httptest.go</span> <span>recorder.go</span> <span>server.go</span>  </p>   <h2 id="pkg-constants">Constants</h2> <p>DefaultRemoteAddr is the default remote address to return in RemoteAddr if an explicit DefaultRemoteAddr isn't set on <a href="#ResponseRecorder">ResponseRecorder</a>. </p>
<pre data-language="go">const DefaultRemoteAddr = "1.2.3.4"</pre> <h2 id="NewRequest">func <span>NewRequest</span>  <span title="Added in Go 1.7">1.7</span> </h2> <pre data-language="go">func NewRequest(method, target string, body io.Reader) *http.Request</pre> <p>NewRequest returns a new incoming server Request, suitable for passing to an <span>http.Handler</span> for testing. </p>
<p>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. </p>
<p>The TLS field is set to a non-nil dummy value if target has scheme "https". </p>
<p>The Request.Proto is always HTTP/1.1. </p>
<p>An empty method means "GET". </p>
<p>The provided body may be nil. If the body is of type *bytes.Reader, *strings.Reader, or *bytes.Buffer, the Request.ContentLength is set. </p>
<p>NewRequest panics on error for ease of use in testing, where a panic is acceptable. </p>
<p>To generate a client HTTP request instead of a server request, see the NewRequest function in the net/http package. </p>
<h2 id="ResponseRecorder">type <span>ResponseRecorder</span>  </h2> <p>ResponseRecorder is an implementation of <span>http.ResponseWriter</span> that records its mutations for later inspection in tests. </p>
<pre data-language="go">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
}
</pre>    <h4 id="example_ResponseRecorder"> <span class="text">Example</span>
</h4> <p>Code:</p> <pre class="code" data-language="go">handler := func(w http.ResponseWriter, r *http.Request) {
    io.WriteString(w, "&lt;html&gt;&lt;body&gt;Hello World!&lt;/body&gt;&lt;/html&gt;")
}

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

</pre> <p>Output:</p> <pre class="output" data-language="go">200
text/html; charset=utf-8
&lt;html&gt;&lt;body&gt;Hello World!&lt;/body&gt;&lt;/html&gt;
</pre>   <h3 id="NewRecorder">func <span>NewRecorder</span>  </h3> <pre data-language="go">func NewRecorder() *ResponseRecorder</pre> <p>NewRecorder returns an initialized <a href="#ResponseRecorder">ResponseRecorder</a>. </p>
<h3 id="ResponseRecorder.Flush">func (*ResponseRecorder) <span>Flush</span>  </h3> <pre data-language="go">func (rw *ResponseRecorder) Flush()</pre> <p>Flush implements <span>http.Flusher</span>. To test whether Flush was called, see rw.Flushed. </p>
<h3 id="ResponseRecorder.Header">func (*ResponseRecorder) <span>Header</span>  </h3> <pre data-language="go">func (rw *ResponseRecorder) Header() http.Header</pre> <p>Header implements <span>http.ResponseWriter</span>. It returns the response headers to mutate within a handler. To test the headers that were written after a handler completes, use the <a href="#ResponseRecorder.Result">ResponseRecorder.Result</a> method and see the returned Response value's Header. </p>
<h3 id="ResponseRecorder.Result">func (*ResponseRecorder) <span>Result</span>  <span title="Added in Go 1.7">1.7</span> </h3> <pre data-language="go">func (rw *ResponseRecorder) Result() *http.Response</pre> <p>Result returns the response generated by the handler. </p>
<p>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. </p>
<p>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. </p>
<p>The Response.Body is guaranteed to be non-nil and Body.Read call is guaranteed to not return any error other than <span>io.EOF</span>. </p>
<p>Result must only be called after the handler has finished running. </p>
<h3 id="ResponseRecorder.Write">func (*ResponseRecorder) <span>Write</span>  </h3> <pre data-language="go">func (rw *ResponseRecorder) Write(buf []byte) (int, error)</pre> <p>Write implements http.ResponseWriter. The data in buf is written to rw.Body, if not nil. </p>
<h3 id="ResponseRecorder.WriteHeader">func (*ResponseRecorder) <span>WriteHeader</span>  </h3> <pre data-language="go">func (rw *ResponseRecorder) WriteHeader(code int)</pre> <p>WriteHeader implements <span>http.ResponseWriter</span>. </p>
<h3 id="ResponseRecorder.WriteString">func (*ResponseRecorder) <span>WriteString</span>  <span title="Added in Go 1.6">1.6</span> </h3> <pre data-language="go">func (rw *ResponseRecorder) WriteString(str string) (int, error)</pre> <p>WriteString implements <span>io.StringWriter</span>. The data in str is written to rw.Body, if not nil. </p>
<h2 id="Server">type <span>Server</span>  </h2> <p>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. </p>
<pre data-language="go">type Server struct {
    URL      string // base URL of form http://ipaddr:port with no trailing slash
    Listener net.Listener

    // EnableHTTP2 controls whether HTTP/2 is enabled
    // on the server. It must be set between calling
    // NewUnstartedServer and calling Server.StartTLS.
    EnableHTTP2 bool // Go 1.14

    // 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
}
</pre>    <h4 id="example_Server"> <span class="text">Example</span>
</h4> <p>Code:</p> <pre class="code" data-language="go">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)
</pre> <p>Output:</p> <pre class="output" data-language="go">Hello, client
</pre>      <h4 id="example_Server_hTTP2"> <span class="text">Example (HTTP2)</span>
</h4> <p>Code:</p> <pre class="code" data-language="go">ts := httptest.NewUnstartedServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
    fmt.Fprintf(w, "Hello, %s", r.Proto)
}))
ts.EnableHTTP2 = true
ts.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)

</pre> <p>Output:</p> <pre class="output" data-language="go">Hello, HTTP/2.0
</pre>   <h3 id="NewServer">func <span>NewServer</span>  </h3> <pre data-language="go">func NewServer(handler http.Handler) *Server</pre> <p>NewServer starts and returns a new <a href="#Server">Server</a>. The caller should call Close when finished, to shut it down. </p>
<h3 id="NewTLSServer">func <span>NewTLSServer</span>  </h3> <pre data-language="go">func NewTLSServer(handler http.Handler) *Server</pre> <p>NewTLSServer starts and returns a new <a href="#Server">Server</a> using TLS. The caller should call Close when finished, to shut it down. </p>   <h4 id="example_NewTLSServer"> <span class="text">Example</span>
</h4> <p>Code:</p> <pre class="code" data-language="go">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)
</pre> <p>Output:</p> <pre class="output" data-language="go">Hello, client
</pre>   <h3 id="NewUnstartedServer">func <span>NewUnstartedServer</span>  </h3> <pre data-language="go">func NewUnstartedServer(handler http.Handler) *Server</pre> <p>NewUnstartedServer returns a new <a href="#Server">Server</a> but doesn't start it. </p>
<p>After changing its configuration, the caller should call Start or StartTLS. </p>
<p>The caller should call Close when finished, to shut it down. </p>
<h3 id="Server.Certificate">func (*Server) <span>Certificate</span>  <span title="Added in Go 1.9">1.9</span> </h3> <pre data-language="go">func (s *Server) Certificate() *x509.Certificate</pre> <p>Certificate returns the certificate used by the server, or nil if the server doesn't use TLS. </p>
<h3 id="Server.Client">func (*Server) <span>Client</span>  <span title="Added in Go 1.9">1.9</span> </h3> <pre data-language="go">func (s *Server) Client() *http.Client</pre> <p>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 <a href="#Server.Close">Server.Close</a>. </p>
<h3 id="Server.Close">func (*Server) <span>Close</span>  </h3> <pre data-language="go">func (s *Server) Close()</pre> <p>Close shuts down the server and blocks until all outstanding requests on this server have completed. </p>
<h3 id="Server.CloseClientConnections">func (*Server) <span>CloseClientConnections</span>  </h3> <pre data-language="go">func (s *Server) CloseClientConnections()</pre> <p>CloseClientConnections closes any open HTTP connections to the test Server. </p>
<h3 id="Server.Start">func (*Server) <span>Start</span>  </h3> <pre data-language="go">func (s *Server) Start()</pre> <p>Start starts a server from NewUnstartedServer. </p>
<h3 id="Server.StartTLS">func (*Server) <span>StartTLS</span>  </h3> <pre data-language="go">func (s *Server) StartTLS()</pre> <p>StartTLS starts TLS on a server from NewUnstartedServer. </p><div class="_attribution">
  <p class="_attribution-p">
    &copy; Google, Inc.<br>Licensed under the Creative Commons Attribution License 3.0.<br>
    <a href="http://golang.org/pkg/net/http/httptest/" class="_attribution-link">http://golang.org/pkg/net/http/httptest/</a>
  </p>
</div>