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

oryband picture oryband  路  3Comments

rawoke083 picture rawoke083  路  3Comments

CodingPapi picture CodingPapi  路  3Comments

lilee picture lilee  路  3Comments

mastrolinux picture mastrolinux  路  3Comments