net/http (client)

net/http client requests with Client.Do, DefaultClient, contexts, body close, and read limits, tested with a fake RoundTripper and no network.

This page is the client side of net/http: building a Request, sending it with Client.Do, and reading the Response. Import the package as "net/http". Handlers, ServeMux, and Server belong on the net/http (server) page. In-memory handler tests belong on net/http/httptest. Cookie jars belong on net/http/cookiejar. net/url parses URLs; it is not a client.

http.Get, http.Head, and http.Post use DefaultClient, which is a usable *Client whose Timeout is zero: official documentation says a Timeout of zero means no timeout. That covers connection time, redirects, and reading the body. Set Timeout on your own Client, or cancel with a Request context from NewRequestWithContext.

Examples use a fake http.RoundTripper and in-memory Response values. They do not open sockets, start a server, or read environment tokens. Outputs were recorded with Go 1.24.0.

Examples were checked against Go 1.24.0. See the official package documentation for the complete API.

Go reference overview →

API index

APISummary
http.DefaultClient, NewRequest, and Client.DoDefaultClient has no overall timeout. Do returns a nil error for 404 and 500 responses from a fake transport. The body is still closed.
http.NewRequestWithContext and io.LimitReaderAttach a context to an outbound request and read only a prefix of the response body. The transport is still a fake RoundTripper.

Do, status codes, and closing the body

Client.Do sends a Request and follows client policy such as redirects and cookies. Official documentation states that an error is returned for client policy or a failure to speak HTTP, and that a non-2xx status code does not cause an error. A 404 or 500 is therefore a Response you must inspect, not usually a non-nil error from Do.

If the error is nil, Response.Body is non-nil and the caller must close it. Official documentation also says the body should be read to EOF and closed so a Transport can reuse a persistent connection. Even with a fake RoundTripper, the examples close the body. The request Body, if any, is closed by the Transport, possibly asynchronously, including on error.

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.

ParameterDescription
method, url, bodyNewRequest arguments. url is a string such as https://example.test/missing. It is not fetched by NewRequest itself. body may be nil.
reqThe 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.
go
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

Official documentation →

Request context and limited reads

NewRequest wraps NewRequestWithContext using context.Background. Official documentation says that for an outbound request the context controls the entire lifetime: obtaining a connection, sending the request, and reading the response headers and body. Cancel the context when the caller no longer needs the result; a zero Client.Timeout does not do that work for you. The context page explains that cancellation is only observed when the call looks at ctx.Done or ctx.Err.

Reading an unbounded Body can use as much memory as the server sends. io.LimitReader caps a client-side read. It is not the same as http.MaxBytesReader, which is intended for incoming request bodies on a server and is on the server page. After a limited read, still close the Body.

http.NewRequestWithContext and io.LimitReader

func NewRequestWithContext(ctx context.Context, method, url string, body io.Reader) (*Request, error)
func LimitReader(r Reader, n int64) Reader

Attach a context to an outbound request and read only a prefix of the response body. The transport is still a fake RoundTripper.

ParameterDescription
ctxControls the outbound request lifetime. This example uses context.Background only to show the API; cancel it in real callers when work should stop.
nThe maximum number of bytes LimitReader will return from the body.

Returns: NewRequestWithContext returns *Request and an error. LimitReader returns an io.Reader that stops after n bytes and then yields EOF.

Errors

  • error — NewRequestWithContext can fail to parse the URL. Do can still fail for transport reasons. A short read from LimitReader is not an error.
  • To test a Handler, official documentation points at net/http/httptest.NewRequest rather than this constructor.
go
package main

import (
	"context"
	"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 main() {
	client := &http.Client{Transport: roundTripFunc(func(req *http.Request) (*http.Response, error) {
		return &http.Response{
			StatusCode: http.StatusOK,
			Status:     "200 OK",
			Body:       io.NopCloser(strings.NewReader("1234567890")),
			Header:     make(http.Header),
			Request:    req,
			Proto:      "HTTP/1.1",
			ProtoMajor: 1,
			ProtoMinor: 1,
		}, nil
	})}

	ctx := context.Background()
	req, err := http.NewRequestWithContext(ctx, http.MethodGet, "https://example.test/ok", nil)
	fmt.Println("new", err)
	resp, err := client.Do(req)
	fmt.Println("do", err, resp.StatusCode)
	limited, err := io.ReadAll(io.LimitReader(resp.Body, 4))
	fmt.Println("read", err, string(limited))
	fmt.Println("close", resp.Body.Close())
}

Expected output

new <nil>
do <nil> 200
read <nil> 1234
close <nil>

Related: context, io.LimitReader, net/http (server) MaxBytesReader

Official documentation →