I'm creating a Golang API, but hit a blocker. For every POST, this is what I get: "error": "sql: converting argument $2 type: unsupported type main.Data, a struct"
I'd like my data to be of format
"name": "test",
"other": {
"age": "",
"height": ""
}
}
How can I achieve this? See the code below, what I've tried so far.
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)
}
I expected the db to be populated with the data of format
"name": "test",
"other": {
"age": "",
"height": ""
}
}
But fails with error:
"error": "sql: converting argument $2 type: unsupported type main.Data, a struct"
You can make this modification:
import "encoding/json"
func (d *Data) Create(db *sql.DB) error {
var jsonOther string
if d.Other != nil {
jsonOther, _ = json.Marshal(d.Other)
err := db.QueryRow(
"INSERT INTO configs(name, other) VALUES($1, $2) RETURNING id",
d.Name, jsonOther).Scan(&d.ID)
if err != nil {
return err
}
return nil
}
Notice that the Other
object is explicitly serialized to JSON and passed as a string