Skip to content

Gin Context: Request vs Gin Context

DodaTech Updated 2026-06-24 1 min read

In this tutorial, you'll learn about Gin Context: Request vs Gin Context. We cover key concepts, practical examples, and best practices.

Gin request context -- Use Gin's c.Request.Context() for context cancellation in handlers instead of creating new background contexts.

The Problem

Gin's c *gin.Context wraps http.Request but developers sometimes use context.Background() for database calls. This ignores client disconnection. Always derive contexts from c.Request.Context().

Wrong

func getUser(c *gin.Context) {
    ctx := context.Background()
    user, err := db.QueryContext(ctx, "SELECT ...")
}

Output:

// Client disconnects but DB query continues
func getUser(c *gin.Context) {
    ctx := c.Request.Context()
    user, err := db.QueryContext(ctx, "SELECT ...")
    if err != nil {
        c.JSON(500, gin.H{"error": err.Error()})
        return
    }
    c.JSON(200, user)
}

Output:

$ curl --max-time 2 http://localhost:8080/user/1
// Query cancelled when client disconnects

Prevention

  • Always pass c.Request.Context() to database and external API calls
  • Never use context.Background() in request-scoped handlers
  • Gin's c.Done() channel works for Gin-specific middleware
  • Check ctx.Err() after long operations to detect cancellation
  • Context cancellation is automatic when the handler returns

Common Mistakes with gin context

  1. Misunderstanding that String is [Char] with poor performance for large text operations
  2. Using foldl instead of foldl' causing stack overflow on large lists
  3. Forgetting deriving (Show, Eq) on custom data types needed for debugging

These mistakes appear frequently in real-world GO code. DodaTech's contributors have identified these patterns through analysis of open-source projects and production systems.

Practice Exercise

Write a pure function that safely divides two integers using Maybe, then test it with edge cases like division by zero and negative numbers.

This exercise reinforces the concepts covered in this guide. Try implementing it before checking online solutions.

FAQ

**Does Gin cancel the context automatically?**

Yes. c.Request.Context() is cancelled when the client disconnects or the handler returns.

What is c.Done() vs c.Request.Context().Done()?

Both work. c.Done() is Gin's wrapper. Prefer c.Request.Context() for portability.

Can I add values to Gin's context?

Yes. Use c.Set("key", value) and c.Get("key") for request-scoped data.


Built by the developers of Doda Browser, DodaZIP, and Durga Antivirus Pro. DodaTech tutorials help Go developers build production-ready software used by millions.

Built by the developers of DodaTech

Doda Browser, DodaZIP & Durga Antivirus Pro