Gin: How to stop a middleware and get response immediately?

Created on 28 Mar 2017  路  3Comments  路  Source: gin-gonic/gin

i'm trying to write a body parser middleware. by design, the middleware will return immediately if an error occurs when fail to decode json. but the middleware acted like that it ignores the return statement and went to next handler.

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()
    }
}

Most helpful comment

@dheeraj2dj Try with

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

This works!

All 3 comments

use Abort before return

@sofish How did it work for you? The following is my code snippet, but am unable to make it work. It doesn't abort.

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

Getting this error : [GIN-debug] [WARNING] Headers were already written. Wanted to override status code 401 with 200

@dheeraj2dj Try with

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

This works!

Was this page helpful?
0 / 5 - 0 ratings

Related issues

libnat picture libnat  路  29Comments

cachafla picture cachafla  路  33Comments

monikaYZ picture monikaYZ  路  24Comments

elliotlings picture elliotlings  路  29Comments

ndbroadbent picture ndbroadbent  路  67Comments