HTTP Clients in Go
net/http is a complete, production-grade HTTP client in the standard library. It is also easy to use badly: the
default client has no timeout, response bodies must be closed, and a 500 response is not an error as far as
http.Get is concerned. This lesson builds a small API client the right way and tests it against a real HTTP server
running inside the same program with net/http/httptest.
A test server in three lines
httptest.NewServer starts an HTTP server on a random loopback port and returns its URL. Whatever handler you give
it plays the API. Everything the client does (TCP connection, HTTP request, headers, status codes) is real:
package main
import (
"encoding/json"
"fmt"
"io"
"net/http"
"net/http/httptest"
"time"
)
type Service struct {
Name string `json:"name"`
Replicas int `json:"replicas"`
}
func main() {
api := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.Header.Get("Authorization") != "Bearer s3cret" {
http.Error(w, `{"error": "invalid token"}`, http.StatusUnauthorized)
return
}
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode([]Service{{"shop-api", 2}, {"worker", 1}})
}))
defer api.Close()
client := &http.Client{Timeout: 5 * time.Second} // never use a client without a timeout
for _, token := range []string{"s3cret", "wrong"} {
req, err := http.NewRequest(http.MethodGet, api.URL+"/v1/services", nil)
if err != nil {
panic(err)
}
req.Header.Set("Authorization", "Bearer "+token)
req.Header.Set("Accept", "application/json")
req.Header.Set("User-Agent", "opsctl/1.0")
resp, err := client.Do(req)
if err != nil {
fmt.Println("request failed:", err) // network-level failure: no response at all
continue
}
func() {
defer resp.Body.Close() // always close, or connections leak
if resp.StatusCode != http.StatusOK {
body, _ := io.ReadAll(io.LimitReader(resp.Body, 1024))
fmt.Printf("HTTP %d: %s", resp.StatusCode, body)
return
}
var services []Service
if err := json.NewDecoder(resp.Body).Decode(&services); err != nil {
fmt.Println("bad JSON:", err)
return
}
fmt.Printf("HTTP %d: %+v\n", resp.StatusCode, services)
}()
}
}HTTP 200: [{Name:shop-api Replicas:2} {Name:worker Replicas:1}]
HTTP 401: {"error": "invalid token"}
Rules visible in the code:
- Set
Timeouton the client.http.Getandhttp.DefaultClientwait forever for a server that never answers. err != nilonly means the request did not complete (DNS, connection refused, timeout). A 401 or 503 is a successful round trip witherr == nil; checkresp.StatusCodeyourself.- Close the body on every path, or the underlying connection cannot be reused and eventually you run out of them.
- Limit what you read from error responses:
io.LimitReaderstops a misbehaving server from feeding you gigabytes.
A reusable client with context and retries
Real tools wrap this in a small client type. context.Context carries a deadline for a whole operation (all retries
included) and lets a caller cancel it, for example on Ctrl+C. The test server below fails twice with 503 before
succeeding, and has a deliberately slow endpoint:
package main
import (
"context"
"encoding/json"
"errors"
"fmt"
"io"
"net/http"
"net/http/httptest"
"strings"
"sync/atomic"
"time"
)
type Client struct {
BaseURL string
Token string
HTTP *http.Client
Retries int
Backoff time.Duration
}
type StatusError struct {
Code int
Body string
}
func (e *StatusError) Error() string { return fmt.Sprintf("HTTP %d: %s", e.Code, e.Body) }
func retryable(code int) bool {
return code == http.StatusTooManyRequests || code >= 500
}
// GetJSON fetches path and decodes it into out, retrying temporary failures (GET is idempotent).
func (c *Client) GetJSON(ctx context.Context, path string, out any) error {
delay := c.Backoff
for attempt := 1; ; attempt++ {
err := c.getOnce(ctx, path, out)
var se *StatusError
temporary := err != nil && (!errors.As(err, &se) || retryable(se.Code)) && ctx.Err() == nil
if err == nil || !temporary || attempt > c.Retries {
return err
}
fmt.Printf(" attempt %d failed (%v), retrying in %s\n", attempt, err, delay)
select {
case <-time.After(delay):
case <-ctx.Done():
return ctx.Err()
}
delay *= 2
}
}
func (c *Client) getOnce(ctx context.Context, path string, out any) error {
req, err := http.NewRequestWithContext(ctx, http.MethodGet, c.BaseURL+path, nil)
if err != nil {
return err
}
req.Header.Set("Authorization", "Bearer "+c.Token)
resp, err := c.HTTP.Do(req)
if err != nil {
return err
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
b, _ := io.ReadAll(io.LimitReader(resp.Body, 256))
return &StatusError{resp.StatusCode, strings.TrimSpace(string(b))}
}
return json.NewDecoder(resp.Body).Decode(out)
}
func main() {
var calls atomic.Int32
mux := http.NewServeMux()
mux.HandleFunc("GET /v1/status", func(w http.ResponseWriter, r *http.Request) {
if calls.Add(1) <= 2 {
http.Error(w, "overloaded", http.StatusServiceUnavailable)
return
}
fmt.Fprint(w, `{"healthy": 5, "degraded": 1}`)
})
mux.HandleFunc("GET /v1/report", func(w http.ResponseWriter, r *http.Request) {
select { // a slow endpoint that gives up when the client goes away
case <-time.After(2 * time.Second):
fmt.Fprint(w, `{}`)
case <-r.Context().Done():
}
})
mux.HandleFunc("GET /v1/missing", func(w http.ResponseWriter, r *http.Request) {
http.NotFound(w, r)
})
srv := httptest.NewServer(mux)
defer srv.Close()
c := &Client{BaseURL: srv.URL, Token: "s3cret", HTTP: &http.Client{Timeout: 10 * time.Second},
Retries: 3, Backoff: 20 * time.Millisecond}
fmt.Println("GET /v1/status")
var status map[string]int
err := c.GetJSON(context.Background(), "/v1/status", &status)
fmt.Println(" result:", status, "error:", err)
fmt.Println("GET /v1/missing")
err = c.GetJSON(context.Background(), "/v1/missing", &status)
fmt.Println(" error:", err)
fmt.Println("GET /v1/report with a 200ms deadline")
ctx, cancel := context.WithTimeout(context.Background(), 200*time.Millisecond)
defer cancel()
err = c.GetJSON(ctx, "/v1/report", &status)
fmt.Println(" deadline exceeded:", errors.Is(err, context.DeadlineExceeded))
}GET /v1/status
attempt 1 failed (HTTP 503: overloaded), retrying in 20ms
attempt 2 failed (HTTP 503: overloaded), retrying in 40ms
result: map[degraded:1 healthy:5] error: <nil>
GET /v1/missing
error: HTTP 404: 404 page not found
GET /v1/report with a 200ms deadline
deadline exceeded: true
- The two 503s were retried with doubling delays; the 404 was returned immediately, because a retry cannot fix it.
- The deadline applied to the whole call.
errors.Is(err, context.DeadlineExceeded)identifies it without parsing the message, which contains the random test-server port and would differ on every run. "GET /v1/status"patterns with a method are Go 1.22+ServeMuxrouting; older code checksr.Methodby hand.
Pointing it at the real API
Nothing in Client knows about httptest. In the real tool, the base URL and token come from flags or the
environment, and the HTTP client may get a tuned transport:
c := &Client{
BaseURL: os.Getenv("CATALOG_URL"), // e.g. https://catalog.example.com
Token: os.Getenv("CATALOG_TOKEN"),
HTTP: &http.Client{
Timeout: 30 * time.Second,
Transport: &http.Transport{
Proxy: http.ProxyFromEnvironment, // honours HTTPS_PROXY / NO_PROXY
MaxIdleConnsPerHost: 10,
TLSHandshakeTimeout: 5 * time.Second,
},
},
Retries: 4,
Backoff: 500 * time.Millisecond,
}
ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM) // Ctrl+C cancels requests
defer stop()signal.NotifyContext turns Ctrl+C or a SIGTERM from Kubernetes into a cancelled context, so in-flight requests
stop and deferred cleanup runs: the Go equivalent of the Bash trap.
Test yourself
resp, err := client.Do(req) returns a 503 response. What is err?
- An error describing the 503
- nil: the HTTP exchange succeeded, so you must check resp.StatusCode
- context.DeadlineExceeded
- io.EOF
What is the timeout of http.Get(url) (the default client)?
- 30 seconds
- 10 seconds
- None: it can wait forever
- It depends on the server
Why test the client with httptest.NewServer instead of a mock interface?
- Mocks are not allowed in Go
- It exercises the real HTTP stack (requests, headers, status codes, timeouts) with no external network
- httptest is faster than function calls
- It records production traffic