Headers were already written. Wanted to override status code 400 with 200

go gin framework to parse json

This error report scenario is: 1. Gin framework, 2. Write POST request method interface, 3. Use structure binding method to accept parameters

The pit phenomenon is: when the structure fails to bind the parameters (that is, when the parameters are incorrect or transmitted incorrectly), the httpcode is 400, no matter how the developer forces the return of the httpcode, the code is 400

Reason: Behaviour – These methods MustBindWith are used under the hood. If there is a binding error, the request is aborted c.AbortWithError(400, err).SetType(ErrorTypeBind). This sets the response status code to 400 and the Content-Type header to text/plain; charset=utf-8. Note that attempting to set the response code after this will result in a warning [GIN-debug] [WARNING] Headers were already written. Wanted to override status code 400 with 422. If you want more control over the behavior, consider using the equivalent method of ShouldBind.

Solution: The method of binding the structure is not applicable [BindJSON] changed to [ShouldBind]

//Receive json data format
param := make(map[string]interface{})
err := c.ShouldBind(&param)
if err != nil {
     panic(&errs.JsonFromatError)
}
photoV, _ := param["photo"].(string) //Interface type to string
photoValue := util.PhotoBase64Start(photoV)

Leave a Reply

Your email address will not be published. Required fields are marked *

en_USEnglish