estou tentando escrever um middleware de analisador de corpo. por design, o middleware retornará imediatamente se um error
ocorrer quando houver falha na decodificação de json. mas o middleware agiu assim, ignorou a instrução return
e foi para o próximo manipulador.
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
antes de return
@sofish Como funcionou para você? A seguir está o meu trecho de código, mas não consigo fazê-lo funcionar. Não aborta.
c.Header("WWW-Authenticate", "Basic realm=\"Authorization Required\"")
c.JSON(http.StatusUnauthorized, gin.H{"Message": "Unauthorized"})
c.Abort()
return
Recebendo este erro: [GIN-debug] [WARNING] Headers were already written. Wanted to override status code 401 with 200
@ dheeraj2dj Experimente com
ctx.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{"Message": "Unauthorized"})
Isso funciona!
Comentários muito úteis
@ dheeraj2dj Experimente com
Isso funciona!