Reputation: 4419
I'm trying to to get a set of data from my database and return them in a json format. However, they are of different types and I seem to be using the wrong return types in my code.
Go:
type Script struct {
Id int `json:"id"`
Type string `json:"type"`
Created_at int `json:"created_at"`
}
type AllContent struct {
New_content []*Script `json:"new_content,omitempty"`
}
func ReadAllContent() [][]interface{} {
err := db.Ping()
if err != nil {
log.Fatal(err)
}
rows, err := db.Query("SELECT id, type, created_at FROM script WHERE user_id = $1", user_id)
if err != nil {
log.Fatal(err)
}
defer rows.Close()
var Type string
var created_at, id int
for rows.Next() {
err := rows.Scan(&id, &Type, &created_at)
if err != nil {
log.Fatal(err)
}
var a []interface{}
var b []interface{}
a = append(a, id, Type, created_at)
b = append(b, a)
}
return b
}
func pingHandler(w http.ResponseWriter, r *http.Request) {
var s []Script
resp := AllContent{New_content: []*Script{}}
m := ReadAllContent()
for i := 0; i < len(m); i++ {
s = append(s, Script{Id: m[i][0], Type: m[i][1], Created_at: m[i][2])
}
for i := 0; i < len(m); i++ {
resp.New_content = append(resp.New_content, &s[i])
}
w.Header().Set("Content-Type", "application/json")
js, _ := json.Marshal(resp)
w.Write(js)
}
I get this error:
cannot use m[i][0] (type interface {}) as type int in field value: need type assertion
What should I resolve?
Upvotes: 0
Views: 53
Reputation:
You can fix the compiler error by adding type assertions:
s = append(s, Script{Id: m[i][0].(int), Type: m[i][1].(string), Created_at: m[i][2].(int))
A better and simpler approach is to return a slice of script objects from ReadAllContent:
func ReadAllContent() []*Script {
var result []*Script
err := db.Ping()
if err != nil {
log.Fatal(err)
}
rows, err := db.Query("SELECT id, type, created_at FROM script WHERE user_id = $1", user_id)
if err != nil {
log.Fatal(err)
}
defer rows.Close()
for rows.Next() {
s := &Script{}
err := rows.Scan(&s.ID, &s.Type, &s.Created_at)
if err != nil {
log.Fatal(err)
}
result = append(result, s)
}
return result
}
You can then encode the return from ReadAllContent directly to JSON:
func pingHandler(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
if err := json.NewEncoder(w).Encode(&AllContent{New_content: ReadAllContent()}); err != nil {
// handle error
}
}
Upvotes: 2