首页 > 文章列表 > 如何在 Gin 中扩展 Context?

如何在 Gin 中扩展 Context?

344 2025-04-23

如何在 Gin 中扩展 Context?

gin context 如何扩展

在 gin 中,如果你需要对 context 进行扩展,可以使用闭包的方式。

比如我们想要自定义一个 c.fail("上传失败") 方法,可以这样写:

type Context struct {
    *gin.Context
}

func (ctx Context) Fail(msg string) {
    ctx.JSON(500, gin.H{
        "message": msg,
    })
}

func NewExtendContext(fn(Context)) gin.HandlerFunc {
    return func(ctx *gin.Context) {
        fn(Context{ctx})
    }
}

func upload(ctx Context) {
    // ...
    ctx.Fail("上传失败")
}

app.Get("/upload", NewExtendContext(upload))

这样,我们就可以在业务代码中调用 ctx.fail("上传失败") 来返回一个失败响应了。

来源:1730276731