问题:golang在嵌套结构中解码JSON请求并作为blob插入数据库

我有一个嵌套结构,用于解码 JSON 请求。

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 类型在 MySQL 中存储合同。为了使它工作,我需要创建一个不同的结构,其中 Contract 作为字符串插入到 DB 中。这可以通过仅使用单个结构以更好的方式完成,还是有任何其他优雅的方式?

解答

database/sqlContract
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.ContractValue
sql := // INSERT INTO ...
svc := // &Service{ ...
db.Exec(sql, svc.ID, svc.Name, svc.Contract)
Contract
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)