Gin: ミドルウェアを停止してすぐに応答を得る方法は?

作成日 2017年03月28日  ·  3コメント  ·  ソース: gin-gonic/gin

ボディパーサーミドルウェアを作成しようとしています。 設計上、jsonのデコードに失敗したときにerrorが発生すると、ミドルウェアはすぐに返されます。 しかし、ミドルウェアはreturnステートメントを無視して、次のハンドラーに移動するように動作しました。

package middleware

import (
    "github.com/gin-gonic/gin"
    "encoding/json"
    "net/http"
)

func BodyParser() gin.HandlerFunc {
    return func(c *gin.Context) {
        var m map[string]interface{}

        decoder := json.NewDecoder(c.Request.Body)

        defer c.Request.Body.Close()

        if err := decoder.Decode(&m); err != nil {
            c.JSON(http.StatusBadRequest, gin.H{"error": "invalid body"})
            return
        }

        c.Set("body", m)
        c.Next()
    }
}

最も参考になるコメント

@ dheeraj2dj試してみてください

ctx.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{"Message": "Unauthorized"})

これはうまくいきます!

全てのコメント3件

使用Abortの前にreturn

@sofishそれはあなたにとってどのように機能しましたか? 以下は私のコードスニペットですが、それを機能させることができません。 中止しません。

c.Header("WWW-Authenticate", "Basic realm=\"Authorization Required\"")
c.JSON(http.StatusUnauthorized, gin.H{"Message": "Unauthorized"})
c.Abort()
return

このエラーの取得: [GIN-debug] [WARNING] Headers were already written. Wanted to override status code 401 with 200

@ dheeraj2dj試してみてください

ctx.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{"Message": "Unauthorized"})

これはうまくいきます!

このページは役に立ちましたか?
0 / 5 - 0 評価

関連する問題

Bloomca picture Bloomca  ·  3コメント

boneq picture boneq  ·  3コメント

frederikhors picture frederikhors  ·  3コメント

mastrolinux picture mastrolinux  ·  3コメント

rawoke083 picture rawoke083  ·  3コメント