0
我試圖從我的數據庫中獲取一組數據並將它們以json格式返回。然而,他們是不同的類型,我似乎在我的代碼中使用了錯誤的返回類型。轉:在json響應中從數據庫複製各種類型的數據
轉到:
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)
}
我得到這個錯誤:
cannot use m[i][0] (type interface {}) as type int in field value: need type assertion
我應該怎麼解決?
#nitpick:你已經命名了返回參數並返回它。我認爲這是在golint(iirc ...可能是錯誤的)中找到的。 – 2014-10-01 00:23:21