You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

咨询Gin-Gonic自定义中间件两种写法的差异原因

Difference Between Two Gin Middleware Patterns

Great question! Let's break down the two approaches and their key differences:

1. Factory Function Pattern (Returning gin.HandlerFunc)

The first pattern uses a function that creates and returns a gin.HandlerFunc:

func MyMiddleware() gin.HandlerFunc { 
    return func (c *gin.Context) { 
        // middleware logic
    } 
}

r := gin.New()
r.Use(MyMiddleware())

The biggest advantage here is parameterization. You can add arguments to the outer function to configure the middleware before returning the actual handler. For example, if you need to pass a logger, API key, or any other dependency/configuration:

func MyMiddleware(logger *log.Logger) gin.HandlerFunc {
    return func(c *gin.Context) {
        logger.Printf("Processing request: %s", c.Request.URL.Path)
        c.Next()
    }
}

// Usage: pass your logger instance when registering
r.Use(MyMiddleware(appLogger))

This makes the middleware reusable across different parts of your app with different configurations.

2. Direct Handler Pattern

The second pattern uses a function that directly matches the gin.HandlerFunc type signature (which is defined as type HandlerFunc func(*Context)):

func MyMiddleware(c *gin.Context) { 
    // middleware logic
}

r := gin.New()
r.Use(MyMiddleware)

This is a simpler, more concise approach for middleware that doesn't need any external configuration or dependencies. Since you're passing the function reference directly, you can't pass additional parameters when registering it—your middleware has to be self-contained or rely on global values.

Core Differences

  • Configuration Flexibility: The factory pattern lets you customize middleware behavior at registration time, while the direct pattern is static.
  • Reusability: Factory functions are ideal for building reusable middleware components that adapt to different contexts, whereas direct handlers are best for one-off, unconfigurable middleware.
  • Invocation: In the first case, you call MyMiddleware() to get the handler; in the second, you pass the function itself (since it already fits the gin.HandlerFunc type).

Both approaches are valid—choose the one that fits your middleware's needs!

内容的提问来源于stack exchange,提问作者cHz

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.29 07:43:30