golang在嵌套结构中解码JSON请求并将其作为blob插入DB [英] golang decode JSON request in nested struct and insert in DB as blob
问题描述
我有一个用于解码JSON请求的嵌套结构.
I have a nested struct which I am using to decode JSON request.
type Service struct {
ID string `json:"id,omitempty" db:"id"`
Name string `json:"name" db:"name"`
Contract struct {
ServiceTime int `json:"service_time"`
Region string `json:"region"`
} `json:"contract" db:"contract"`
}
我正在使用Blob类型将Contract存储在MySQL中.为了使其工作,我将需要使用Contract作为字符串创建一个不同的结构以插入到DB中.可以仅通过使用单个结构以更好的方式完成此操作,还是有其他优雅的方法?
I am using blob type to store Contract in MySQL. To make it work , I would be needing to create a different struct with Contract as string to insert in DB. Can this be done in better way by using single struct only or is there any other elegant way ?
推荐答案
这取决于您用来与数据库对话的内容,但是如果您使用的是database/sql
和提供对此功能的驱动程序,则可以Contract
类型实现 Valuer 接口.
This depends on what you use to talk to the database, but if you're using database/sql
and a driver that provides support for this you can have your Contract
type implement the Valuer interface.
type Service struct {
ID string `json:"id,omitempty" db:"id"`
Name string `json:"name" db:"name"`
Contract Contract `json:"contract" db:"contract"`
}
type Contract struct {
ServiceTime int `json:"service_time"`
Region string `json:"region"`
}
func (c *Contract) Value() (driver.Value, error) {
if c != nil {
b, err := json.Marshal(c)
if err != nil {
return nil, err
}
return string(b), nil
}
return nil, nil
}
然后在执行查询时,只需传入Service.Contract
字段,驱动程序应调用Value
方法.
And then when you're executing the query just pass in the Service.Contract
field and the driver should call the Value
method.
sql := // INSERT INTO ...
svc := // &Service{ ...
db.Exec(sql, svc.ID, svc.Name, svc.Contract)
并且为了能够从db中检索blob并将其解组到Contract
中,您可以使其实现扫描器界面,再次,如果有类型实现此功能,则驱动程序应调用它.
And to be able to retrieve the blob back from db and unmarshal it back into Contract
you can have it implement the Scanner interface, again, if a type implements this the driver is expected to call it.
func (c *Contract) Scan(src interface{}) error {
var data []byte
if b, ok := src.([]byte); ok {
data = b
} else if s, ok := src.(string); ok {
data = []byte(s)
}
return json.Unmarshal(data, c)
}
// ...
sql := // SELECT * FROM ...
svc := // &Service{ ...
db.QueryRow(sql, 123).Scan(&svc.ID, &svc.Name, &svc.Contract)
这篇关于golang在嵌套结构中解码JSON请求并将其作为blob插入DB的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!