Gin
01 / 02

Gin: Middleware, Recovery & When It Fits

Gin: Middleware, Recovery & When It Fits

Custom Middleware

func requestLogger() gin.HandlerFunc {
    return func(c *gin.Context) {
        start := time.Now()
        c.Next()  // hand off to the next middleware/handler
        log.Printf("%s %s -> %d in %v", c.Request.Method, c.Request.URL.Path, c.Writer.Status(), time.Since(start))
    }
}

Aborting a Request From Middleware

func authMiddleware() gin.HandlerFunc {
    return func(c *gin.Context) {
        if c.GetHeader("Authorization") == "" {
            c.AbortWithStatusJSON(401, gin.H{"error": "unauthorized"})
            return
        }
        c.Next()
    }
}

Recovering From Panics

gin.Recovery() (included by default in gin.Default()) catches a panic during request handling and returns a 500 response instead of crashing the entire server process from a single request's unrecovered panic.

Debug vs. Release Mode

gin.SetMode(gin.ReleaseMode)

// Disables debug-level logging and dev conveniences --
// appropriate for production deployments

Why Choose Gin Over Plain net/http

net/http can fully build an API, but Gin's routing, middleware chaining, binding/validation, and JSON helpers reduce the boilerplate a developer would otherwise write by hand -- a productivity layer for common HTTP-service needs.

Keep your own version of these notes — editable, searchable, and organised by your stack.

Start free