Gin in the wider system · 7 MIN READ

Upstream calls from Gin: one shared client, the request deadline, a bounded body and your own error codes

Call an upstream HTTP API from a Gin handler through a shared, budgeted http.Client and map every failure to your own 404, 502 or 504 without leaking upstream details.

Most Gin services are also HTTP clients: they call a payment provider, an inventory service or a search cluster while their own caller waits. Every such call borrows the caller's time, a pooled connection and memory for the reply. Done naively, one slow or misbehaving upstream turns into piled-up goroutines, exhausted sockets and error responses that quote another team's database errors to your users.

gin · A MAP OF THE IDEA

  1. Share one client
  2. Derive the call context
  3. Bound the body
  4. Map to your own errors

Useful when

  • Upstream failures become stable, documented error codes.
  • A hung upstream costs one bounded budget, not a stuck goroutine.

Watch out

  • A new client or Transport per request defeats connection reuse.
  • Forwarding upstream bodies or headers leaks internal details.
  • LimitReader alone truncates silently; read the limit plus one byte.

Implementation & operation cost: One client constructor, an error-mapping function and a fake RoundTripper for tests; tuning pool sizes and timeouts needs load tests against the real upstream.

01

What goes wrong with http.Get inside a handler

http.Get uses http.DefaultClient, which has no overall Timeout. DefaultTransport bounds dialing and the TLS handshake but sets no ResponseHeaderTimeout, so an upstream that accepts the connection and never answers holds the handler goroutine until something cancels it, and nothing will unless the request carries a context. Building a new http.Client with a new Transport per request is the opposite mistake: every Transport owns its own connection pool, so keep-alive never helps and idle sockets pile up. io.ReadAll on the body trusts the upstream to be small. Copying the upstream status and body into c.Data turns their 500 into yours and their SQL error into your public API. The fix is four rules: one client built at startup, a per-call context derived from the request, a cap on the bytes you read, and an explicit mapping from upstream outcomes to your own responses.

02

Build the client once, with budgets on the Transport

The Transport owns connections, so it is where the phase timeouts live: dialing, the TLS handshake and the wait for response headers. Client.Timeout covers the whole exchange including the body and acts as a backstop. Construct the client in the composition root described in the config-startup lesson and inject it into the handler struct, so a test can swap the Transport without touching the handler.

go
func newInventoryClient() *http.Client {
	dialer := &net.Dialer{Timeout: 2 * time.Second, KeepAlive: 30 * time.Second}
	transport := &http.Transport{
		Proxy:                  http.ProxyFromEnvironment,
		DialContext:            dialer.DialContext,
		ForceAttemptHTTP2:      true, // a custom DialContext turns HTTP/2 off otherwise
		TLSHandshakeTimeout:    3 * time.Second,
		ResponseHeaderTimeout:  2 * time.Second,
		ExpectContinueTimeout:  time.Second,
		IdleConnTimeout:        90 * time.Second,
		MaxIdleConns:           100,
		MaxIdleConnsPerHost:    32, // the default of 2 churns connections under load
		MaxConnsPerHost:        64, // a hard cap: extra requests wait for a free connection
		MaxResponseHeaderBytes: 64 << 10,
	}
	return &http.Client{
		Transport: transport,
		Timeout:   5 * time.Second, // a backstop; the per-call context is the real budget
		CheckRedirect: func(*http.Request, []*http.Request) error {
			return http.ErrUseLastResponse // an API that redirects is misconfigured
		},
	}
}
Read the code

Run this fragment in your own native environment; it dials real hosts. ForceAttemptHTTP2 matters because the Transport documentation says a custom DialContext or TLS config disables HTTP/2 unless it is set. ResponseHeaderTimeout counts from the moment the request is fully written until headers arrive; it does not cover reading the body. MaxIdleConnsPerHost defaults to http.DefaultMaxIdleConnsPerHost, which is 2, so a busy service closes and reopens connections constantly without a higher value. MaxConnsPerHost makes excess requests queue for a connection, and that queueing time still counts against each request's context. CheckRedirect returning http.ErrUseLastResponse makes Do return the 3xx response unfollowed; the SSRF lesson in the security course explains why following redirects needs its own policy.

03

Pass the request context, cap the body, translate the result

The program wires an Inventory client into a Gin route. Stock derives a 50 ms budget from c.Request.Context(), builds the request with http.NewRequestWithContext, sends this service's own token and reads at most 64 KiB. The upstream is a fake http.RoundTripper, the interface the real Transport implements, so the genuine http.Client code path runs without a socket. Seven SKUs exercise success, a missing item, an upstream 500 with internal headers, an oversized body, a refused connection, a hung upstream and a client that disconnected first.

go
package main

import (
	"cmp"
	"context"
	"encoding/json"
	"errors"
	"fmt"
	"io"
	"net/http"
	"net/http/httptest"
	"net/url"
	"strings"
	"time"

	"github.com/gin-gonic/gin"
)

// fakeInventory plays the upstream API. A RoundTripper answers in-process,
// so the real http.Client code path runs without opening a socket.
type fakeInventory struct{ seen []string }

func (f *fakeInventory) RoundTrip(req *http.Request) (*http.Response, error) {
	if err := req.Context().Err(); err != nil {
		return nil, err // http.Transport also fails fast on a finished context
	}
	_, deadline := req.Context().Deadline()
	f.seen = append(f.seen, fmt.Sprintf("%s %s deadline=%t auth=%q cookie=%q",
		req.Method, req.URL.Path, deadline, req.Header.Get("Authorization"), req.Header.Get("Cookie")))
	switch sku := strings.TrimPrefix(req.URL.Path, "/v1/stock/"); sku {
	case "DOWN":
		return nil, errors.New("dial tcp 192.0.2.10:443: connect: connection refused")
	case "SLOW":
		<-req.Context().Done() // a hung upstream: only our deadline ends the wait
		return nil, req.Context().Err()
	case "ERR":
		return reply(req, 500, `pq: relation "stock" does not exist`, "X-Backend-Host", "db-3.internal"), nil
	case "BIG":
		return reply(req, 200, `{"sku":"BIG","notes":"`+strings.Repeat("x", 1<<20)+`"}`), nil
	case "NOPE":
		return reply(req, 404, `{"message":"no such sku"}`), nil
	default:
		return reply(req, 200, `{"sku":"`+sku+`","available":4,"warehouse":"wh-eu-2","cost_cents":1250}`), nil
	}
}

func reply(req *http.Request, status int, body string, kv ...string) *http.Response {
	h := http.Header{"Content-Type": {"application/json"}}
	for i := 0; i+1 < len(kv); i += 2 {
		h.Set(kv[i], kv[i+1])
	}
	return &http.Response{StatusCode: status, Header: h, Body: io.NopCloser(strings.NewReader(body)),
		ContentLength: int64(len(body)), Request: req}
}

var errUnknownSKU = errors.New("inventory: unknown sku")

// Stock is the subset of the upstream document this service relies on.
type Stock struct {
	SKU       string `json:"sku"`
	Available int    `json:"available"`
}

type Inventory struct {
	Client  *http.Client // shared by every request: it owns the connection pool
	BaseURL string
	Token   string        // this service's credential, never the caller's
	Budget  time.Duration // per-call deadline, below the route's own budget
	MaxBody int64
}

func (inv *Inventory) Stock(ctx context.Context, sku string) (Stock, error) {
	ctx, cancel := context.WithTimeout(ctx, inv.Budget)
	defer cancel()
	req, err := http.NewRequestWithContext(ctx, http.MethodGet, inv.BaseURL+"/v1/stock/"+url.PathEscape(sku), nil)
	if err != nil {
		return Stock{}, err
	}
	req.Header.Set("Accept", "application/json")
	req.Header.Set("Authorization", "Bearer "+inv.Token)
	resp, err := inv.Client.Do(req)
	if err != nil {
		return Stock{}, err
	}
	defer resp.Body.Close()
	if resp.StatusCode != http.StatusOK {
		io.Copy(io.Discard, io.LimitReader(resp.Body, 4<<10)) // drain a little so the connection can be reused
		if resp.StatusCode == http.StatusNotFound {
			return Stock{}, errUnknownSKU
		}
		return Stock{}, fmt.Errorf("inventory: status %d", resp.StatusCode)
	}
	body, err := io.ReadAll(io.LimitReader(resp.Body, inv.MaxBody+1))
	if err != nil {
		return Stock{}, fmt.Errorf("inventory: read: %w", err)
	}
	if int64(len(body)) > inv.MaxBody {
		return Stock{}, fmt.Errorf("inventory: body over %d bytes", inv.MaxBody)
	}
	var s Stock
	if err := json.Unmarshal(body, &s); err != nil {
		return Stock{}, fmt.Errorf("inventory: decode: %w", err)
	}
	return s, nil
}

var logs []string // stands in for a structured logger

// fail maps an upstream failure to this API's own error format.
func fail(c *gin.Context, err error) {
	status, code := http.StatusBadGateway, "inventory_unavailable"
	switch {
	case errors.Is(err, errUnknownSKU):
		c.JSON(http.StatusNotFound, gin.H{"error": gin.H{"code": "unknown_sku"}})
		return
	case c.Request.Context().Err() != nil:
		logs = append(logs, "client went away: "+err.Error())
		c.AbortWithStatus(499) // nobody reads this; it only labels logs and metrics
		return
	case errors.Is(err, context.DeadlineExceeded):
		status, code = http.StatusGatewayTimeout, "inventory_timeout"
	}
	logs = append(logs, err.Error()) // the cause goes to logs, never to the client
	c.JSON(status, gin.H{"error": gin.H{"code": code}})
}

func main() {
	gin.SetMode(gin.TestMode)
	upstream := &fakeInventory{}
	inv := &Inventory{
		Client:  &http.Client{Transport: upstream},
		BaseURL: "https://inventory.internal.example",
		Token:   "svc-test-token",
		Budget:  50 * time.Millisecond,
		MaxBody: 64 << 10,
	}
	r := gin.New()
	r.GET("/products/:sku/stock", func(c *gin.Context) {
		s, err := inv.Stock(c.Request.Context(), c.Param("sku"))
		if err != nil {
			fail(c, err)
			return
		}
		c.JSON(http.StatusOK, s) // our type: warehouse and cost_cents never reach the client
	})

	for _, sku := range []string{"A-1", "NOPE", "ERR", "BIG", "DOWN", "SLOW", "GONE"} {
		req := httptest.NewRequest(http.MethodGet, "/products/"+sku+"/stock", nil)
		req.Header.Set("Authorization", "Bearer end-user-token")
		req.Header.Set("Cookie", "session=s3cr3t")
		if sku == "GONE" {
			ctx, cancel := context.WithCancel(req.Context())
			cancel() // the client disconnected before the upstream call
			req = req.WithContext(ctx)
		}
		w := httptest.NewRecorder()
		r.ServeHTTP(w, req)
		fmt.Printf("%s -> %d %s\n", sku, w.Code, cmp.Or(w.Body.String(), "(no body)"))
		for _, line := range logs {
			fmt.Println("  log:", line)
		}
		logs = logs[:0]
		if sku == "A-1" {
			fmt.Println("  upstream saw:", upstream.seen[0])
		}
		if sku == "ERR" {
			leaked := w.Header().Get("X-Backend-Host") != "" || strings.Contains(w.Body.String(), "pq:")
			fmt.Println("  upstream detail leaked:", leaked)
		}
	}
}
Read the code

The A-1 line shows what the upstream received: a deadline on the context, the service token, and no trace of the caller's Authorization or Cookie headers. NOPE maps the upstream 404 to the domain error errUnknownSKU and then to this API's own 404. ERR proves nothing leaks: the client sees inventory_unavailable while the status goes to the log, and X-Backend-Host and the pq: text stay behind. BIG reads 64 KiB plus one byte, sees the extra byte and refuses, instead of decoding a silently truncated document. DOWN and SLOW both fail inside Client.Do, and errors.Is(err, context.DeadlineExceeded) separates the timeout (504) from the refused connection (502). For GONE the request context is already canceled; fail records 499, the nginx convention for a client that closed the request, purely for logs and metrics.

04

Status codes are yours: 502, 504, 404 and the client that left

RFC 9110 defines 502 Bad Gateway as an invalid response from an upstream and 504 Gateway Timeout as no timely response. Use 502 for refused connections, upstream 5xx, unreadable, oversized or malformed bodies, and 504 when your per-call budget expires. errors.Is(err, context.DeadlineExceeded) also catches an expired Client.Timeout, because in the Go 1.27 source the timeout error net/http returns has an Is method that matches context.DeadlineExceeded. An upstream 404 for a SKU is a domain fact, so it becomes your 404 with your error code. An upstream 400, 401 or 403 usually means your service built a bad request or holds a wrong credential: that is your bug, so answer 502 and alert, and never pass a 401 through, or the client will think its own login failed. Never echo the upstream body, its Set-Cookie, Server or routing headers, or its status text; the problem-details lesson defines the envelope to use instead. And do not forward the caller's Authorization or Cookie: the upstream would act with the user's authority and log their credentials. Send a service credential and pass the user's identity as data when the upstream needs it.

05

Read the body deliberately: limits, draining and tolerant decoding

io.LimitReader alone truncates silently, so read MaxBody+1 bytes and treat a longer result as a failure. When you do not set Accept-Encoding yourself, the Transport asks for gzip and decompresses transparently, which means the limit applies to decoded bytes, the number that protects your memory; if you set the header yourself, you must decompress and bound the result yourself, as the compression lesson in this unit does for request bodies. Always close the body, and remember that an HTTP/1.1 connection returns to the pool only when its body was read to EOF: drain a few kilobytes on error paths and let anything larger close the connection. Decode into a struct holding only the fields you use. encoding/json ignores unknown fields, so the upstream can add warehouse or cost_cents without breaking you, and those fields never reach your clients because your type does not have them. If a proxy in front of the upstream sometimes returns HTML error pages, check the Content-Type before decoding.

06

Test the client at the RoundTripper seam

A fake RoundTripper records each outgoing request and returns scripted responses or errors, including one that blocks on the request context to model a hung upstream. Assert the method, the escaped path, the headers you send and the ones you must not forward, and that a deadline is present. Each row of your error mapping becomes one test case, exactly as the program's seven SKUs do. Keep one integration test against a real server, httptest.NewServer or a staging upstream, run in your own environment, for what only a real Transport shows: dial and header timeouts, TLS, HTTP/2 and connection reuse. In production, count upstream calls by outcome (ok, not_found, 5xx, timeout, too_large) next to a latency histogram per upstream, so a spike of 502s says which dependency failed and how; the metrics lesson shows how to keep those labels bounded.

TAKE THIS WITH YOU

Build one http.Client with Transport timeouts at startup, derive each call's context from c.Request.Context(), read at most a fixed number of bytes, and translate every upstream outcome into your own 404, 502 or 504 without forwarding their bodies, their headers or your caller's credentials.

Check your understanding

A Gin handler's call to an upstream API exceeds its per-call context deadline. What should the handler return to its own client?

Go to the source

Progress stays in this browser. No account needed.