Golang GIN 接收结构体切片(前端对象数组)

想接收前端这样的数据格式:【json数组】

复制代码
[
    {
        "password": "casso",
        "mobile": "13456789999",
        "nick_name": "go",
        "icon": "地址"
    },
    {
        "password": "casso",
        "mobile": "13456789999",
        "nick_name": "go",
        "icon": "地址"
    }
]
复制代码

GO代码

复制代码
//TestUser 创建测试用户
type TestUser struct {
    PassWord string `json:"password" binding:"required"`  // 密码
    Mobile   string `json:"mobile" binding:"required"`    // 电话
    NickName string `json:"nick_name"` // 昵称
    Icon     string `json:"icon"`      // 头像
}
// CreateTeast 创建测试用户
func CreateTeast(c *gin.Context){
    var postData []TestUser
    if err := c.ShouldBind(&postData); err != nil {
        response.ReturnJSON(c, http.StatusOK, statuscode.InvalidParam.Code,statuscode.InvalidParam.Msg, nil)
        return
    }
    // 走到这里,postData 里面就有数据了
}
复制代码

稍微复杂的数据结构

复制代码
type Cards struct {
    No    string `json:"no"`
    Local string `json:"local"`
}

type Per struct {
    Name string  `json:"name"`
    Card []Cards `json:"card"`
    Age  int     `json:"age"`
}

// CreateTeast 创建测试用户
func CreateTeast(c *gin.Context) {
    var postData Per
    if err := c.ShouldBind(&postData); err != nil {
        response.ReturnJSON(c, http.StatusOK, statuscode.InvalidParam.Code, statuscode.InvalidParam.Msg, nil)
        return
    }
    // 走到这里,postData 里面就有数据了
}
复制代码

总结:

  • 最重要的一点是:GIN框架,GET 方法并不能使用ShouldBind等这类方法获取数据,所以还是要按照规范来。
posted @   李若盛开  阅读(534)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
· DeepSeek 开源周回顾「GitHub 热点速览」
点击右上角即可分享
微信分享提示