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()
}
}
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!
Most helpful comment
@dheeraj2dj Try with
This works!