JSONGin Web框架JSONBody结构体Struct字典Map
环境
go version go1.14.3 windows/amd64
github.com/gin-gonic/gin v1.6.3
1. 结论
使用场景 | 函数 |
---|---|
单次绑定 | ShouldBindJSON > BindJSON |
多次绑定⭐ | ShouldBindBodyWith |
ShouldBindJSONEOFShouldBindJSONcontext.request.body.sawEOFfalseShouldBindBodyWith
BindJSONBindJSON
以下为范例:
// 以下是用于存储JSON数据的结构体
type MsgJson struct {
Msg string `json:"msg"`
}
// 单次绑定使用 ShouldBindJSON 方法
func bindExample(c *gin.Context) {
// ---> 声明结构体变量
var a MsgJson
// ---> 绑定数据
if err := c.ShouldBindJSON(&a); err != nil {
c.AbortWithStatusJSON(
http.StatusInternalServerError,
gin.H{"error": err.Error()})
return
}
// --> 返回
c.JSON(http.StatusOK, gin.H{"msg": "ok"})
return
}
// 多次绑定优先使用 ShouldBindBodyWith 方法
func bindWithRightWay(c *gin.Context) {
// ---> 声明两个结构体变量用于存储JSON数据
var a, b MsgJson
// ---> 第一次解析(注意第二个参数是 binding.JSON)
if err := c.ShouldBindBodyWith(&a, binding.JSON); err != nil {
c.AbortWithStatusJSON(
http.StatusInternalServerError,
gin.H{"error": err.Error()})
return
}
// ---> 第二次解析
if err := c.ShouldBindBodyWith(&b, binding.JSON); err != nil {
c.AbortWithStatusJSON(
http.StatusInternalServerError,
gin.H{"error": err.Error()})
return
}
// ---> 返回
c.JSON(http.StatusOK, gin.H{"msg": "ok"})
return
}
2. EOF错误复现
EOFShouldBindJSONShouldBindBodyWith
type MsgJson struct {
Msg string `json:"msg"`
}
func main() {
r := gin.Default()
r.POST("/v2", bindWithError)
_ = r.Run("127.0.0.1:9001")
}
func bindWithError(c *gin.Context) {
var a, b MsgJson
if err := c.ShouldBindJSON(&a); err != nil {....}
// ---> 注意,这里会出现EOF报错
if err := c.ShouldBindJSON(&b); err != nil {....}
.......
return
}
PostmanGoland
ShouldBindBodyWith
ShouldBindBodyWithShouldBindWithrequestsBodyBodyBodyShouldBindWith
func (c *Context) ShouldBindBodyWith(obj interface{}, bb binding.BindingBody) (err error) {
var body []byte
// ---> 先看上下文是否已经有Body的Bytes数据
if cb, ok := c.Get(BodyBytesKey); ok {
if cbb, ok := cb.([]byte); ok {
body = cbb
}
}
// ---> 如果Body不为空的情况下,读取Body数据并写入上下文
if body == nil {
body, err = ioutil.ReadAll(c.Request.Body)
if err != nil {
return err
}
c.Set(BodyBytesKey, body)
}
return bb.BindBody(body, obj)
}
流程图