Skip to content
Tutorials Center
My learning

Topics

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.

Go
client := &http.Client{Timeout: 10 * time.Second}
resp, err := client.Do(req)

Try it

Go Timeout and context cancellation

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.

Go Headers, redirects and cookies

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

Go
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 satisfy errors.Is(err, context.DeadlineExceeded) and are a net.Error whose Timeout() is true; a canceled context gives context.Canceled.
  • Status codes 4xx and 5xx are not errors.
  • Do consumes req.Body. To retry, rebuild the request or use req.GetBody, which NewRequest sets for common body types.
  • Timeout also stops a slow body read after Do has returned.
  • A request with a body will only be redirected automatically when GetBody is 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 Timeout as a global safety net. Both can be used at once.
  • Fine-grained limits live on the Transport: DialContext timeouts, TLSHandshakeTimeout, ResponseHeaderTimeout, MaxIdleConns, MaxIdleConnsPerHost (default 2), IdleConnTimeout. Clone http.DefaultTransport and adjust it: t := http.DefaultTransport.(*http.Transport).Clone().
  • Proxy: the default transport reads HTTP_PROXY, HTTPS_PROXY and NO_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 POST makes the follow-up request a GET without the body; 307 and 308 keep method and body. Sensitive headers such as Authorization are not forwarded to a different domain.
  • Always close resp.Body; see http.Get().
  • Testing: inject a custom Transport (a type with RoundTrip) to fake responses without a network.