go - 无法中止()上下文 - Gin

标签 go go-gin

我有以下 Gin 中间件:

func CheckAppId(appC *core.Context) gin.HandlerFunc {
    return func(c *gin.Context) {
        //get Basic Auth credentials
        appId, token, _ := c.Request.BasicAuth()

        if appId == "" {
            c.JSON(http.StatusOK, gin.H{"code": "MISSING_APP_ID", "message": "Your request is missing an application id"})
            return //this is being ignored???
        }

        c.Next() //this still gets hit
    }
}

但是如果 appId == "" JSON 被返回并且 c.Next() 也被执行。这是预期的行为吗?

编辑 我以为问题已经售出,但同样的事情似乎正在发生。我现在有:

func CheckAppId(appC *core.Context) gin.HandlerFunc {
    return func(c *gin.Context) {
        //get Basic Auth credentials
        appId, token, _ := c.Request.BasicAuth()

        if appId == "" {
            //I'm getting this JSON in the response
            c.JSON(http.StatusOK, gin.H{"code": "MISSING_APP_ID", "message": "Your request is missing an application id"})
            c.Abort()
        }

        //find app_id in database
        app := core.App{}
        err := appC.Database.C("apps").Find(bson.M{"id" : appId}).One(&app)
        if err != nil { //no app found
            //and I'm getting this JSON in the response
            c.JSON(http.StatusOK, gin.H{"code": "INVALID_APP_ID", "message": "The application id provided could not be found"})
            c.Abort()
        }

        c.Next()
    }
}

在对 API 的调用中,我同时收到“MISSING_APP_ID”Json 和“INVALID_APP_ID”Json

最佳答案

查看 Gin API 文档,您需要调用 context.Abort()而不是从您的方法返回。

Abort stops the system to continue calling the pending handlers in the chain. Let's say you have an authorization middleware that validates if the request is authorized if the authorization fails (the password does not match). This method (Abort()) should be called in order to stop the execution of the actual handler.

所以在你的具体情况下

if appId == "" {
    c.JSON(http.StatusOK, gin.H{"code": "MISSING_APP_ID", "message": "Your request is missing an application id"})
    c.Abort()
    return
}

关于go - 无法中止()上下文 - Gin ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32467002/

相关文章:

google-app-engine - 如何验证 JWT 签名?

Golang包 block 变量线程安全吗?

go - Gin 错误 : listen tcp: lookup addr on : no such host

go - 我是否需要生成多个 Go Web 服务器实例才能充分利用我的 CPU?

go - 在 Go 网络应用程序中加载 key 的最佳实践是什么?

mysql - 如何使用 sqlx 共享 mysql 连接?

go - 池模式和原型(prototype)模式有什么区别?

mysql - 从Golang Gorm查询中获取选定的值

go - 如何让多个模型在 gorm 中自动迁移

go - 出现错误时如何关闭websockethandle