go gin框架解析json

Gin框架踩坑——[GIN-debug] [WARNING] Headers were already written. Wanted to override status code 400 with 200


这个报错场景为 : 1.Gin框架、2.编写POST请求方式接口、3.使用结构体绑定方式接受参数

 

该坑现象为 : 当结构体绑定参数失败时(即参数有误、传错时),httpcode为400,无论开发者如何强制返回httpcode,code就是400

原因 : 行为 – 这些方法MustBindWith在引擎盖下使用。如果存在绑定错误,则请求被中止c.AbortWithError(400, err).SetType(ErrorTypeBind)。这将响应状态码设置为400,并将Content-Type标题设置为text/plain; charset=utf-8。请注意,如果在此之后尝试设置响应代码,将会导致警告[GIN-debug] [WARNING] Headers were already written. Wanted to override status code 400 with 422。如果您希望更好地控制行为,请考虑使用ShouldBind等效的方法。

 

 

解决方法 : 绑定结构体的方法一概不适用【BindJSON】改为【ShouldBind】

//接收json数据形式
param := make(map[string]interface{})
err := c.ShouldBind(&param)
if err != nil {
    panic(&errs.JsonFromatError)
}
photoV, _ := param["photo"].(string) //接口类型转字符串
photoValue := util.PhotoBase64Start(photoV)

 

posted on 2021-12-28 11:21  星河赵  阅读(1090)  评论(0编辑  收藏  举报

导航