我有以下 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/