http.DefaultClient, NewRequest, and Client.Do
var DefaultClient = &Client{}
func NewRequest(method, url string, body io.Reader) (*Request, error)
func (c *Client) Do(req *Request) (*Response, error)DefaultClient has no overall timeout. Do returns a nil error for 404 and 500 responses from a fake transport. The body is still closed.
| Parameter | Description |
|---|---|
method, url, body | NewRequest arguments. url is a string such as https://example.test/missing. It is not fetched by NewRequest itself. body may be nil. |
req | The request passed to Do. For outbound requests, use NewRequest or NewRequestWithContext, not httptest.NewRequest. |
Returns: NewRequest returns *Request and an error. Do returns *Response and an error. A nil Do error still requires you to close Response.Body.
Errors
error— Do errors are for transport or policy failures, not for 4xx or 5xx status codes. Official documentation says any returned error has type *url.Error.
- The printed DefaultClient.Timeout is the zero duration, which official documentation defines as no timeout. This example does not use DefaultClient to send a request.
- example.test and the response bodies are sample data. The RoundTripper never dials a host.
package main
import (
"fmt"
"io"
"net/http"
"strings"
)
type roundTripFunc func(*http.Request) (*http.Response, error)
func (f roundTripFunc) RoundTrip(req *http.Request) (*http.Response, error) {
return f(req)
}
func response(req *http.Request, code int, body string) *http.Response {
return &http.Response{
StatusCode: code,
Status: fmt.Sprintf("%d %s", code, http.StatusText(code)),
Body: io.NopCloser(strings.NewReader(body)),
Header: make(http.Header),
Request: req,
Proto: "HTTP/1.1",
ProtoMajor: 1,
ProtoMinor: 1,
}
}
func main() {
fmt.Printf("default_timeout=%v zero=%t\n", http.DefaultClient.Timeout, http.DefaultClient.Timeout == 0)
client := &http.Client{Transport: roundTripFunc(func(req *http.Request) (*http.Response, error) {
if req.URL.Path == "/missing" {
return response(req, http.StatusNotFound, "missing"), nil
}
return response(req, http.StatusInternalServerError, "broken"), nil
})}
req, err := http.NewRequest(http.MethodGet, "https://example.test/missing", nil)
fmt.Println("new", err)
resp, err := client.Do(req)
fmt.Println("do404", err, resp.StatusCode)
body, _ := io.ReadAll(resp.Body)
fmt.Println("close", resp.Body.Close())
fmt.Println("body", string(body))
req, _ = http.NewRequest(http.MethodGet, "https://example.test/broken", nil)
resp, err = client.Do(req)
fmt.Println("do500", err, resp.StatusCode)
fmt.Println("close500", resp.Body.Close())
}Expected output
default_timeout=0s zero=true
new <nil>
do404 <nil> 404
close <nil>
body missing
do500 <nil> 500
close500 <nil>Related: net/url, errors, net/http (server), net/http/cookiejar