亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

未能中止()上下文 - 杜松子酒

未能中止()上下文 - 杜松子酒

Go
江戶川亂折騰 2021-11-08 10:57:04
我有以下 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
    }


查看完整回答
反對 回復 2021-11-08
?
寶慕林4294392

TA貢獻2021條經驗 獲得超8個贊

你需要做:


if condition {

  c.Abort()

} else {

  c.Next()

}

解釋


(注意:這建立在@Landers 的回答之上)


c.Abort()只是設置一些內部標志,以某種方式標記上下文,指示異常終止。這是有道理的,它是一個不返回任何內容的無參數方法,因此您只是為了它的副作用而調用它。


同樣的事情 c.Next()


由于 go 的控制流(沒有異常或跳轉),很明顯這兩個方法不會立即采取任何行動,而是為下一階段“設置舞臺”,想象一下調用您的CheckAppIdfunc 的Gins 代碼:


// gin code

doStuff()

ctx := getContext()


// this is your CheckAppId

nextAction := FindAction()

nextAction(&ctx)


// here the context is evaluated to see if you either abort or continue.

checkContextStatus(&ctx)

因此,如果您正在調用c.Abort(),然后c.Next()您將覆蓋中止指示。


查看完整回答
反對 回復 2021-11-08
  • 2 回答
  • 0 關注
  • 215 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號