Go Reference ยท Networking and the Web
Go http.Client type
Reference for Go http.Client: Timeout, per-request contexts, NewRequestWithContext, Do, redirects, cookie jars, Transport settings and connection reuse.
http.Client sends HTTP requests and returns responses. It holds the policies that apply to many requests: an overall timeout, how redirects are handled, an optional cookie jar, and a Transport that owns the connection pool.
Create one client and reuse it for the life of the program. Clients are safe for concurrent use, and connection reuse only works when requests share a Transport. For anything beyond a toy script, avoid http.DefaultClient, because it has no timeout.
client := &http.Client{Timeout: 10 * time.Second}
resp, err := client.Do(req)
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.
Syntax
type Client struct { Transport RoundTripper CheckRedirect func(req *Request, via []*Request) error Jar CookieJar Timeout time.Duration } func (c *Client) Do(req *Request) (*Response, error) func (c *Client) Get(url string) (*Response, error) func (c *Client) Head(url string) (*Response, error) func (c *Client) Post(url, contentType string, body io.Reader) (*Response, error) func (c *Client) PostForm(url string, data url.Values) (*Response, error) func (c *Client) CloseIdleConnections() func NewRequest(method, url string, body io.Reader) (*Request, error) func NewRequestWithContext(ctx context.Context, method, url string, body io.Reader) (*Request, error)
| Field | Description |
|---|---|
Transport |
Performs a single request and owns the connection pool. nil means http.DefaultTransport. |
CheckRedirect |
Called before following a redirect. Return an error to stop, or http.ErrUseLastResponse to return the redirect response itself. nil allows up to 10 redirects. |
Jar |
A CookieJar (such as net/http/cookiejar) that stores and sends cookies. nil ignores cookies. |
Timeout |
Limit for the whole exchange, including connection, redirects and reading the body. 0 means no limit. |
Errors and edge cases:
- Failure returns a
*url.Error. Timeouts satisfyerrors.Is(err, context.DeadlineExceeded)and are anet.ErrorwhoseTimeout()is true; a canceled context givescontext.Canceled. - Status codes 4xx and 5xx are not errors.
Doconsumesreq.Body. To retry, rebuild the request or usereq.GetBody, whichNewRequestsets for common body types.Timeoutalso stops a slow body read afterDohas returned.- A request with a body will only be redirected automatically when
GetBodyis available (for 307 and 308).
Usage notes
- Reuse the client. Creating a client per request throws away keep-alive connections and slows everything down.
- Prefer contexts for per-request deadlines, and
Timeoutas a global safety net. Both can be used at once. - Fine-grained limits live on the
Transport:DialContexttimeouts,TLSHandshakeTimeout,ResponseHeaderTimeout,MaxIdleConns,MaxIdleConnsPerHost(default 2),IdleConnTimeout. Clonehttp.DefaultTransportand adjust it:t := http.DefaultTransport.(*http.Transport).Clone(). - Proxy: the default transport reads
HTTP_PROXY,HTTPS_PROXYandNO_PROXY. - Retries are your job. The client retries only in narrow cases (an idle connection that broke). Retry with backoff yourself, and only for idempotent requests.
- Redirects change the method: a 301, 302 or 303 answer to a
POSTmakes the follow-up request aGETwithout the body; 307 and 308 keep method and body. Sensitive headers such asAuthorizationare not forwarded to a different domain. - Always close
resp.Body; seehttp.Get(). - Testing: inject a custom
Transport(a type withRoundTrip) to fake responses without a network.
Related
http.Get(),http.Request, net/http, context- Lessons: HTTP client, Context