我有以下 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
2 回答

一只斗牛犬
TA貢獻1784條經驗 獲得超2個贊
查看 Gin API 文檔,您需要調用context.Abort()而不是從您的方法返回。
Abort 停止系統繼續調用鏈中的掛起處理程序。假設您有一個授權中間件,如果授權失?。艽a不匹配),它會驗證請求是否獲得授權。應調用此方法 (Abort()) 以停止實際處理程序的執行。
所以在你的具體情況下
if appId == "" { c.JSON(http.StatusOK, gin.H{"code": "MISSING_APP_ID", "message": "Your request is missing an application id"}) c.Abort() return }
- 2 回答
- 0 關注
- 215 瀏覽
添加回答
舉報
0/150
提交
取消