概括我正在嘗試將多個 postgres 表中的數據寫入嵌套的 Go 結構,以便在我的 Web 應用程序中返回對 GET 請求的單個 json 響應。問題從 Go 最佳實踐的角度來看,我聲明嵌套結構的方式是合理的,還是有理由避免這種方法并以另一種方式來做?我在步驟 3中做錯了什么來阻止我的代碼工作?(我擔心答案是“一切”)到目前為止我所擁有的我已經聲明了我的結構type MainObject struct { SubObjects []struct { SpecificDetail string `json:"specific-detail"` } `json:"sub-object"` ...(other []structs)...}我已經從表中檢索了行func getMainObjectHandler(w http.ResponseWriter, r *http.Request) { ...(database connnection)... MainObjectID := r.URL.Query().Get("moid") if MainObjectID != "null" { NewMainObject := MainObject{} SubObjectDetail_rows, err := db.Query("SELECT specific_detail from the_table WHERE moid= '" + MainObjectID + "'") if err != nil { log.Fatalf("could not execute query: %v", err) } ...(other db.Query rows)...我嘗試(但失?。⑿袛祿嫿ǖ浇Y構中。 for SubObjectDetail_rows.Next() { SpecificDetail := NewMainObject.SubObject.SpecificDetail{} SubObjectDetail_rows.Scan(&SpecificDetail) SubObject = append(SubObject, SpecificDetail) } NewMainObject = append(MainObject, SubObject) defer persona_rows.Close()最后,我設置了 Marshal 并寫入。 NMOListBytes, err := json.Marshal(NewMainObject) if err != nil { fmt.Println(fmt.Errorf("Error: %v", err)) w.WriteHeader(http.StatusInternalServerError) return } w.Write(NMOListBytes)
1 回答

慕沐林林
TA貢獻2016條經驗 獲得超9個贊
首先,請在創建 SQL 查詢時使用占位符以避免注入:
// db.Query("SELECT specific_detail from the_table WHERE moid= '" + MainObjectID + "'") // not this
db.Query("SELECT specific_detail from the_table WHERE moid=?", MainObjectID)
除非您使用的框架像GORM您不能Scan()使用單個結構值。從文檔:
Scan 將當前行中的列復制到 dest 指向的值中。dest 中的值數必須與 Rows 中的列數相同。
看起來您正在從數據庫查詢中提取 JSON,因為您只查詢一列,因此您可能想要:
var bs []byte // get raw JSON bytes
err = SubObjectDetail_rows.Scan(&bs)
if err != nil { /* always check errors */ }
然后將它們解組到您的結構中:
err = json.Unmarshal(bs, &SpecificDetail)
if err != nil { /* ... */ }
- 1 回答
- 0 關注
- 109 瀏覽
添加回答
舉報
0/150
提交
取消