【发布时间】:2019-05-20 11:01:03
【问题描述】:
我正在创建一个 Golang API,但遇到了阻止程序。对于每个 POST,这就是我得到的:
"error": "sql: converting argument $2 type: unsupported type main.Data, a struct"
我希望我的数据具有格式
"name": "test",
"other": {
"age": "",
"height": ""
}
}
我怎样才能做到这一点?请参阅下面的代码,到目前为止我已经尝试过。
model.go
type Data struct {
ID int `json:"id"`
Name string `json:"name,omitempty"`
Other *Other `json:"other,omitempty"`
}
type Other struct {
Age string `json:"host,omitempty"`
Height string `json:"database,omitempty"`
}
func (d *Data) Create(db *sql.DB) error {
err := db.QueryRow(
"INSERT INTO configs(name, other) VALUES($1, $2) RETURNING id",
d.Name, &d.Other).Scan(&d.ID)
if err != nil {
return err
}
return nil
}
controller.go
...
func (a *App) createData(w http.ResponseWriter, r *http.Request) {
var d Data
decoder := json.NewDecoder(r.Body)
if err := decoder.Decode(&d); err != nil {
fmt.Print(err)
fatalError(w, http.StatusBadRequest, "Invalid request")
return
}
defer r.Body.Close()
if err := d.Create(a.DB); err != nil {
fatalError(w, http.StatusInternalServerError, err.Error())
return
}
jsonResponse(w, http.StatusCreated, d)
}
我希望数据库中填充格式数据
"name": "test",
"other": {
"age": "",
"height": ""
}
}
但因错误而失败:
"error": "sql: converting argument $2 type: unsupported type main.Data, a struct"
【问题讨论】:
-
扫描字符串中的其他 JSON。之后,您可以将其转换为 JSON。
-
你能解释一下吗?
-
DB 驱动程序将每一列扫描为 []byte,然后默认将其转换为数据类型,它不会将 jsonb 的值扫描到结构中,要么您必须编写自定义扫描仪函数或读取string 和 json 中的列解组它。
标签: postgresql go mux