0Pricing
Go Academy · Lesson

Gin Middleware: Auth and Logging

Writing and registering Gin middleware

Gin Middleware: Auth and Logging is a free Go Academy lesson on CoddyKit — lesson 4 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the Go Academy learning path, one of 4 lessons in the course, and your progress syncs across the web and the CoddyKit app.

Gin middleware signature

Gin middleware is a gin.HandlerFunc that calls c.Next() to pass control to the next handler, or c.Abort() to stop the chain.

func MyMiddleware() gin.HandlerFunc {
    return func(c *gin.Context) {
        // before handler
        c.Next()
        // after handler
    }
}

Applying middleware globally

Use r.Use to apply middleware to all routes:

r := gin.New()
r.Use(gin.Logger())
r.Use(gin.Recovery())

Logging middleware

Gin's built-in gin.Logger() logs method, path, status, and latency. For structured logging, replace it with a custom middleware using zap or slog:

func ZapLogger(logger *zap.Logger) gin.HandlerFunc {
    return func(c *gin.Context) {
        start := time.Now()
        c.Next()
        logger.Info("request",
            zap.String("method", c.Request.Method),
            zap.String("path", c.FullPath()),
            zap.Int("status", c.Writer.Status()),
            zap.Duration("latency", time.Since(start)),
        )
    }
}

Auth middleware

Validate a JWT or API key in middleware and abort with 401 if invalid:

func AuthRequired() gin.HandlerFunc {
    return func(c *gin.Context) {
        token := c.GetHeader("Authorization")
        claims, err := validateJWT(token)
        if err != nil {
            c.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{"error": "invalid token"})
            return
        }
        c.Set("user", claims)
        c.Next()
    }
}

Passing data via context

Store data with c.Set("key", value) and retrieve it in handlers with c.Get("key") or the typed helpers like c.MustGet:

user, _ := c.Get("user")
claims := user.(*Claims)

Recovery middleware

gin.Recovery() catches panics and returns a 500 response. Customise it to log the stack trace or send to an error tracking service:

r.Use(gin.CustomRecovery(func(c *gin.Context, recovered any) {
    log.Printf("panic: %v", recovered)
    c.AbortWithStatusJSON(500, gin.H{"error": "internal server error"})
}))

CORS middleware

Add CORS headers with github.com/gin-contrib/cors:

r.Use(cors.New(cors.Config{
    AllowOrigins:     []string{"https://example.com"},
    AllowMethods:     []string{"GET", "POST", "PUT"},
    AllowHeaders:     []string{"Authorization", "Content-Type"},
    AllowCredentials: true,
}))

Rate limiting middleware

Use a token bucket per IP with golang.org/x/time/rate inside middleware to limit request rates.

Request ID middleware

Generate a unique request ID per request and attach it to the context and response header:

func RequestID() gin.HandlerFunc {
    return func(c *gin.Context) {
        id := uuid.New().String()
        c.Set("requestID", id)
        c.Header("X-Request-ID", id)
        c.Next()
    }
}

Group-level middleware

Apply middleware to a specific group instead of globally:

admin := r.Group("/admin")
admin.Use(AuthRequired(), AdminOnly())
admin.GET("/users", listUsers)

Middleware execution order

Middleware runs in registration order before the handler, and in reverse order after c.Next() returns. Think of it like an onion — each layer wraps the next.

Quick Check

How does Gin middleware stop a request from reaching the handler?

Recap: Gin Middleware

Key points:

  • HandlerFunc returning gin.HandlerFunc; call c.Next() to continue
  • c.Set/c.Get to pass data through the chain
  • c.AbortWithStatusJSON to stop chain and send error
  • Apply globally with r.Use or per-group with group.Use

Frequently asked questions

Is the “Gin Middleware: Auth and Logging” lesson free?

Yes — the full text of “Gin Middleware: Auth and Logging” is free to read here on the web, and the Go Academy course includes 4 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the Go Academy course, upgrade to CoddyKit PRO.

What will I learn in “Gin Middleware: Auth and Logging”?

Writing and registering Gin middleware You practise Go Academy with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.

Do I need any experience to start Go Academy?

No prior experience is required. Go Academy on CoddyKit is structured for beginners through advanced learners; this is — lesson 4 of 4, so you can start here or from the beginning and move at your own pace.

How long does the “Gin Middleware: Auth and Logging” lesson take?

Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.

Can I write and run code in this Go Academy lesson?

Yes. Every Go Academy lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.

All lessons in this course

  1. Gin Router and Route Groups
  2. Request Binding and Validation
  3. Response Helpers and Status Codes
  4. Gin Middleware: Auth and Logging
← Back to Go Academy