使用Go-Gin绑定数据,实现一对多关系
时间:2024-02-16
浏览:324
作者:佚名
你在学习Golang相关的知识吗?本文《使用Go-Gin绑定数据,实现一对多关系》,主要介绍的内容就涉及到,如果你想提升自己的开发能力,就不要错过这篇文章,大家要知道编程理论基础和实战操作都是不可或缺的哦!
问题内容
我是 golang 和 gin 框架的新手,我创建了两个模型
type product struct {
gorm.model
name string
media []media
}
type media struct {
gorm.model
uri string
productid uint
}
我发送了一个 post 请求来保存新产品,正文是:
{
"name": "product1",
"media": [
"https://server.com/image1",
"https://server.com/image2",
"https://server.com/image3",
"https://server.com/video1",
"https://server.com/video2"
]
}
我使用此代码保存了一个新产品
product := product{}
if err := context.shouldbindjson(product); err != nil { // <-- here the error
context.string(http.statusbadrequest, fmt.sprintf("err: %s", err.error()))
return
}
tx := db.create(&product)
if tx.error != nil {
context.string(http.statusbadrequest, fmt.sprintf("err: %s", tx.error))
return
}
返回错误信息为
err: json: cannot unmarshal string into Go struct field Product.Media of type models.Media
我知道 shouldbindjson 无法将 media-string 转换为 media-object,但是执行此操作的最佳实践是什么?
正确答案
您的负载与型号不匹配。在 json 正文中,media 是一个字符串数组,而在模型中,它是一个具有两个字段和嵌入式 gorm 模型的结构。
如果您无法更改当前设置的任何内容,请在 media 上实施 UnmarshalJSON 并从原始字节设置 uri 字段。在相同的方法中,您还可以将 productid 初始化为某些内容(如果需要)。
func (m *media) unmarshaljson(b []byte) error {
m.uri = string(b)
return nil
}
然后绑定将按预期工作:
product := Product{}
// pass a pointer to product
if err := context.ShouldBindJSON(&product); err != nil {
// handle err ...
return
}
fmt.Println(product) // {Product1 [{"https://server.com/image1" 0} ... }好了,本文到此结束,带大家了解了《使用Go-Gin绑定数据,实现一对多关系》,希望本文对你有所帮助!关注golang学习网公众号,给大家分享更多Golang知识!
本文内容来源于互联网,如有侵权请联系删除。
近期热门
11.18
11.15
站内热门
最新文章
11.20
11.20
11.20
11.20
热门专题
