Gin: [WARNING] Headers were already written. Wanted to override status code 400 with 201

Created on 27 May 2016  ·  6Comments  ·  Source: gin-gonic/gin

It is working fine with localhost, but when i uploaded the app to aws ec2 i'm getting this warning. Records are created in database but i wasn't able to return the 201 status.

this is my code

//insert record to database
result := handler.db.Create(&newRoom)

//check if record is created
if result.RowsAffected > 0 {
c.JSON(http.StatusCreated, newRoom)
} else {
//display error message
errMsg := &ErrMsg{Message: result.Error.Error()}
c.JSON(http.StatusBadRequest,errMsg)
c.AbortWithStatus(http.StatusBadRequest)
}

Most helpful comment

I have already figured this out.. this code c.Bind(&newIncident) throws an error but i'm not checking it.
now my code is err := c.Bind(&newIncident) and found out that i'm missing to set a value for a specific field in my POST request.

All 6 comments

try adding “return” statement at the place you want to terminate. Just like as this :
...
c.JSON(http.StatusCreated, newRoom)
return
...
c.JSON(http.StatusBadRequest,errMsg)
c.AbortWithStatus(http.StatusBadRequest)
return

not working :(

You call -

c.JSON(http.StatusBadRequest,errMsg)
c.AbortWithStatus(http.StatusBadRequest)

c.JSON sends http.StatusBadRequest and then you send http.StatusBadRequest again with the call to AbortWithStatus.
You should only call one of them. Use return as the exit statement.

I have already figured this out.. this code c.Bind(&newIncident) throws an error but i'm not checking it.
now my code is err := c.Bind(&newIncident) and found out that i'm missing to set a value for a specific field in my POST request.

This was caused by PR #587. Fix is in #633.

You could use this until it's fixed.

func BindJSON(c *gin.Context, obj interface{}) error {
    if err := binding.JSON.Bind(c.Request, obj); err != nil {
        c.Error(err).SetType(gin.ErrorTypeBind)
        return err
    }
    return nil
}

Check #855

Was this page helpful?
0 / 5 - 0 ratings

Related issues

olegsobchuk picture olegsobchuk  ·  3Comments

frederikhors picture frederikhors  ·  3Comments

ccaza picture ccaza  ·  3Comments

mastrolinux picture mastrolinux  ·  3Comments

iiinsomnia picture iiinsomnia  ·  3Comments