Go core
Browse topics

HTTP client requests

Version
1.27
Review
Draft

Summary#

Build a request with http.NewRequestWithContext and send it with Client.Do. When the error is nil, close the response body. Reuse clients and set a time limit through Client.Timeout or the request context.

Syntax#

go
req, err := http.NewRequestWithContext(ctx, http.MethodGet, url, nil)
if err != nil {
	return err
}
res, err := client.Do(req)
if err != nil {
	return err
}
defer res.Body.Close()

Example#

go
package main

import (
	"context"
	"fmt"
	"io"
	"net/http"
	"net/http/httptest"
	"time"
)

func fetch(ctx context.Context, client *http.Client, url string) error {
	req, err := http.NewRequestWithContext(ctx, http.MethodGet, url, nil)
	if err != nil {
		return err
	}
	req.Header.Set("Accept", "text/plain")

	res, err := client.Do(req)
	if err != nil {
		return err
	}
	defer res.Body.Close()

	body, err := io.ReadAll(res.Body)
	if err != nil {
		return err
	}
	fmt.Printf("%d %q\n", res.StatusCode, body)
	return nil
}

func main() {
	server := httptest.NewServer(http.HandlerFunc(
		func(w http.ResponseWriter, r *http.Request) {
			if r.URL.Path != "/status" {
				http.NotFound(w, r)
				return
			}
			fmt.Fprint(w, "ok as "+r.Header.Get("Accept"))
		}))
	defer server.Close()

	client := server.Client()
	client.Timeout = 5 * time.Second
	for _, path := range []string{"/status", "/missing"} {
		if err := fetch(context.Background(), client, server.URL+path); err != nil {
			fmt.Println(err)
		}
	}
}

Expected output#

Text
200 "ok as text/plain"
404 "404 page not found\n"

Common mistakes#

A 404 or 500 response does not make Do return an error, so check StatusCode. The zero value of Client.Timeout means no client time limit. Without a context deadline, a request through http.DefaultClient can wait far longer than intended.

Version applicability#

Client and Do work from Go 1.0. Client.Timeout arrived in Go 1.3, httptest.Server.Client in Go 1.9 and NewRequestWithContext in Go 1.13. The example requires Go 1.16 for io.ReadAll. In Go 1.27, closing an HTTP/1 response body also drains unread content up to a conservative limit to help connection reuse.

Sources#

Attribution
DevLookup contributors
License
CC-BY-4.0