Gin Middleware: Auth and Logging
Writing and registering Gin middleware
Gin Middleware: Auth and Logging is a free Go Academy lesson on CoddyKit. This is lesson 4 of 4. Any 3 lessons of this learning path are free to read in full — after that, CoddyKit PRO unlocks every lesson, plus hands-on practice with a built-in code editor and a 24/7 AI tutor. It is part of the Go Academy learning path, and your progress syncs across the web and the CoddyKit app. The Go Academy course includes 4 lessons in total.
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
Learn Go with an AI tutor — free
Write and run real code in your browser, get instant help from a 24/7 AI tutor, and pick up where you left off on the web or in the app.
- Courses
- 51
- Lessons
- 203
Frequently Asked Questions
Is the “Gin Middleware: Auth and Logging” lesson free?
Yes — any 3 lessons of the Go Academy learning path, including “Gin Middleware: Auth and Logging”, are free to read in full here on the web. After that, CoddyKit PRO unlocks every lesson, plus interactive practice with a built-in code editor and a 24/7 AI tutor. The Go Academy course includes 4 lessons in total.
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, so you can start here or from the beginning and move at your own pace. This is lesson 4 of 4.
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
- Gin Router and Route Groups
- Request Binding and Validation
- Response Helpers and Status Codes
- Gin Middleware: Auth and Logging