Gin and your data · 7 MIN READ

*gin.Context is a pooled struct, not your request context: pass c.Request.Context() to stores and goroutines

Predict what *gin.Context returns as a context.Context under each ContextWithFallback setting and give stores and background work a context that is actually canceled, or deliberately not.

store.Query(c) compiles because *gin.Context implements context.Context, and in a default Gin engine it quietly throws away cancellation, deadlines and tracing values. The context passed to data access decides whether a query stops when its client leaves and whether background work outlives the response. Gin hands you two candidates, and only one of them is a real request context.

gin · A MAP OF THE IDEA

  1. Take c.Request.Context()
  2. Pass ctx to every store
  3. Copy data, never keep c
  4. Detach with WithoutCancel

Useful when

  • Cancellation, deadlines and trace values reach every store call regardless of engine flags.
  • Background work has an explicit owner, budget and shutdown path.

Watch out

  • Never use c or c.Writer after the handler returns; the pool hands it to the next request.
  • context.WithoutCancel also drops the deadline, so add your own timeout and shutdown hook.

Implementation & operation cost: Threading ctx through every service signature and typing c.Request.Context() at each call site; detached work needs its own lifetime management.

01

Two contexts travel with every Gin request

c.Request.Context() belongs to net/http. The server cancels it when the client's connection closes, when an HTTP/2 stream is reset, or when ServeHTTP returns, and middleware derives deadlines and values from it with WithTimeout and WithValue. *gin.Context is something else: a mutable struct that the engine takes from a sync.Pool for each request, fills with the request, route params and keys, and puts back when the chain returns. It implements Deadline, Done, Err and Value so that it can be passed where a context.Context is expected, but those four methods are an adapter whose behavior depends on an engine flag. The request-deadlines lesson showed what happens when a hung store is given c. This lesson takes the adapter apart, follows c back into the pool and works out what c.Copy is actually for.

02

Read the adapter in the v1.12.0 source

In context.go, Deadline, Done and Err first call hasRequestContext, which is true only when engine.ContextWithFallback is set and c.Request has a context. Otherwise Deadline reports ok=false, Done returns nil and Err returns nil. A nil channel is never ready, so a select on c.Done() waits forever, and a driver that checks ctx.Err() before each round trip never finds a reason to stop. Value has a fixed lookup order. The key gin.ContextRequestKey, the constant 0 of type gin.ContextKeyType, returns c.Request. The string gin.ContextKey returns c itself. Any other string key is looked up in c.Keys. Only after that, and only with fallback on, does the lookup reach c.Request.Context(). Typed keys, which context.WithValue users and tracing libraries rely on, therefore return nil by default. A typed key stored with c.Set is never found through Value at all, because only string keys consult c.Keys; the middleware-basics lesson met the same gap from the other side. Both gin.New() and gin.Default() leave ContextWithFallback false.

03

Hand the same store both contexts

The program models a driver that refuses work for a finished context and reads a trace ID the way an instrumented client would. A middleware stores the trace ID in the request context and a tenant in c.Keys. The same routes run on two engines, fallback off and on, with a request whose context carries a deadline and whose client has already gone. The last request starts work that runs after the handler has returned and the request context has been canceled, which is what net/http does when ServeHTTP returns.

go
package main

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

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

// traceKey is a typed context key, the way tracing libraries store spans.
type traceKey struct{}

// Store models a database driver: it refuses work for a finished context
// and reads request-scoped values from the context it is given.
type Store struct{ queries int }

func (s *Store) Query(ctx context.Context) string {
	if err := ctx.Err(); err != nil {
		return "skipped: " + err.Error()
	}
	s.queries++
	trace, _ := ctx.Value(traceKey{}).(string)
	return fmt.Sprintf("ran query %d, trace=%q", s.queries, trace)
}

// tracing stores a trace ID in the request context and a tenant in c.Keys.
func tracing(c *gin.Context) {
	ctx := context.WithValue(c.Request.Context(), traceKey{}, "t-42")
	c.Request = c.Request.WithContext(ctx)
	c.Set("tenant", "acme")
	c.Next()
}

func newRouter(fallback bool, store *Store, later *[]func()) *gin.Engine {
	r := gin.New()
	r.ContextWithFallback = fallback
	r.Use(tracing)
	r.GET("/inspect", func(c *gin.Context) {
		_, hasDeadline := c.Deadline()
		c.String(http.StatusOK, "Deadline ok=%t, Done nil=%t, Err=%v, trace=%v, tenant=%v",
			hasDeadline, c.Done() == nil, c.Err(), c.Value(traceKey{}), c.Value("tenant"))
	})
	r.GET("/via-gin", func(c *gin.Context) {
		c.String(http.StatusOK, "%s", store.Query(c)) // compiles: *gin.Context is a context.Context
	})
	r.GET("/via-request", func(c *gin.Context) {
		c.String(http.StatusOK, "%s", store.Query(c.Request.Context()))
	})
	r.GET("/after", func(c *gin.Context) {
		req, cp := c.Request, c.Copy()
		detached := context.WithoutCancel(c.Request.Context())
		c.Set("tenant", "changed after Copy")
		*later = append(*later,
			func() { fmt.Println("  copy shares the request:", cp.Request == req) },
			func() { fmt.Println("  copy keeps its own Keys: tenant =", cp.Value("tenant")) },
			func() { fmt.Println("  store(cp.Request.Context()):", store.Query(cp.Request.Context())) },
			func() { fmt.Println("  store(WithoutCancel):", store.Query(detached)) },
		)
		c.Status(http.StatusAccepted)
	})
	return r
}

// call sends one request whose context carries a deadline and, if gone is
// true, has already been canceled, as when a client disconnects.
func call(r http.Handler, path string, gone bool) string {
	ctx, cancel := context.WithDeadline(context.Background(), time.Date(2100, 1, 1, 0, 0, 0, 0, time.UTC))
	defer cancel()
	if gone {
		cancel()
	}
	w := httptest.NewRecorder()
	r.ServeHTTP(w, httptest.NewRequest(http.MethodGet, path, nil).WithContext(ctx))
	return w.Body.String()
}

func main() {
	gin.SetMode(gin.TestMode)
	store := &Store{}
	var later []func()
	off := newRouter(false, store, &later)
	on := newRouter(true, store, &later)

	fmt.Println("c as context.Context, client gone:")
	fmt.Println("  fallback off:", call(off, "/inspect", true))
	fmt.Println("  fallback on: ", call(on, "/inspect", true))

	fmt.Println("store calls when the client is gone:")
	fmt.Println("  store(c), fallback off:", call(off, "/via-gin", true))
	fmt.Println("  store(c.Request.Context()):", call(off, "/via-request", true))
	fmt.Println("  store(c), fallback on:", call(on, "/via-gin", true))
	fmt.Println("store(c.Request.Context()), client still here:", call(off, "/via-request", false))

	fmt.Println("work that runs after the handler returned:")
	ctx, cancel := context.WithCancel(context.Background())
	w := httptest.NewRecorder()
	off.ServeHTTP(w, httptest.NewRequest(http.MethodGet, "/after", nil).WithContext(ctx))
	cancel() // net/http cancels the request context once ServeHTTP returns
	for _, f := range later {
		f()
	}
}
Read the code

With fallback off, c reports no deadline, a nil Done channel and a nil Err for a request whose context is both deadlined and canceled. Only the string key tenant survives, because Value finds it in c.Keys, while the typed trace key comes back nil. store(c) therefore runs a query for a client that left and loses the trace ID, and store(c.Request.Context()) sees context.Canceled on either engine. With fallback on, c delegates and behaves like the request context. In the /after handler, c.Copy shares the *http.Request, so the copy's request context is canceled as soon as the request ends, while its Keys are a snapshot: the c.Set after Copy does not reach it. context.WithoutCancel keeps the trace value and drops the cancellation. The deferred closures capture req, cp and detached, never c.

04

The handler returns and the pool takes c back

engine.ServeHTTP takes a *gin.Context from engine.pool, points it at the new writer and request, resets its params, keys, errors and query cache, runs the chain and puts it back. Identity therefore belongs to a pool slot, not to a request. A goroutine that kept c after the handler returned holds a pointer that the next request will fill: c.Param returns another caller's ID, c.Keys holds another principal or nothing, c.Request is a stranger's request, and with fallback on c.Done becomes the stranger's cancellation, so your background work stops when someone else disconnects. Every one of those reads is a data race with the reset in the next ServeHTTP. ContextWithFallback fixes none of it, and even c.Request.Context(), captured honestly before returning, is canceled right after ServeHTTP returns. The race detector reports the bug only when a test actually reuses the context while the goroutine still reads it, so drive handlers that start goroutines with a burst of requests under go test -race.

05

What c.Copy hands a goroutine, and what it does not

Copy builds a new Context that shares the same *http.Request, clones Keys with maps.Clone, copies Params and keeps the full path and the engine. It detaches the writer: the copy's underlying ResponseWriter is nil, so a write through cp.Writer panics instead of corrupting a recycled response, and its handler index is set to the abort value, so cp.Next does nothing. maps.Clone is shallow, so a pointer or slice stored in Keys is still shared with the handler. Errors and Accepted are not copied, and no lifetime is extended. Use Copy when a goroutine needs request data such as params, keys or c.FullPath() after the handler returns. Use neither c nor the copy as the goroutine's context: with fallback off it is never canceled, and with fallback on it is canceled the moment the response is done. Build the work's input as a value and give it a context you own.

go
func (h *Handlers) publish(c *gin.Context) {
	ev := AuditEvent{Route: c.FullPath(), NoteID: c.Param("id"), Tenant: tenantFrom(c)}
	base := context.WithoutCancel(c.Request.Context()) // keeps trace values, drops cancellation
	h.wg.Add(1)
	go func() {
		defer h.wg.Done()
		ctx, cancel := context.WithTimeout(base, 5*time.Second)
		defer cancel()
		stop := context.AfterFunc(h.shutdown, cancel) // also stop when the process drains
		defer stop()
		if err := h.audit.Write(ctx, ev); err != nil {
			h.log.ErrorContext(ctx, "audit write failed", "err", err)
		}
	}()
	c.Status(http.StatusAccepted)
}
Read the code

This fragment belongs to a real service and runs in your own environment; Handlers, AuditEvent and tenantFrom are your types. The event is a plain value built before the goroutine starts, so the goroutine never touches c. WithoutCancel also drops the deadline, so the goroutine sets its own five-second budget, and context.AfterFunc cancels it when the service's shutdown context ends; shutdown then waits on h.wg. The log call still carries the trace values from the request. Work that must survive a crash belongs in a durable queue instead, as the context-workers lesson explains.

06

Decide on ContextWithFallback once, then review for c

Make one rule for the codebase: functions below the HTTP layer take ctx context.Context as their first parameter, and handlers pass c.Request.Context(). The rule works with any engine and is obvious in review. Turning ContextWithFallback on is still a reasonable safety net, because helpers that accept a context.Context then receive cancellation and tracing values when someone passes c by mistake. Set it once while building the engine; it is a plain field read on every call, so changing it while serving is a data race. Expect behavior to change when you flip it: code that was silently never canceled starts returning context.Canceled, which usually exposes a goroutine that kept c. Neither setting rescues retention, and typed keys stored with c.Set still never reach Value. The compiler accepts c wherever a context is expected, so add a small go/analysis check that reports a *gin.Context passed to a context.Context parameter, and keep a test like the program's that sends a canceled request and asserts the store saw it.

TAKE THIS WITH YOU

Pass c.Request.Context() to stores and goroutines. *gin.Context is a pooled struct whose context methods go dead unless ContextWithFallback is set, c.Copy copies request data rather than a lifetime, and detached work needs WithoutCancel plus a deadline you own.

Check your understanding

In Gin v1.12.0 with gin.New() defaults, a handler calls store.Query(c) and the client disconnects mid-query. What does the store see through that context?

Go to the source

Progress stays in this browser. No account needed.