大家好,我正在使用 golang 構建一個超級簡單的 API。我有這個 json 數據從 POST 請求傳遞并存儲在我的數據庫中。我想獲取 tts 數據,它是一個整數數組,對該數組取平均值并將其放在 ttc 列中,并在 json 響應中返回該數字。我很難做到這一點,我們將不勝感激。下面是我的源代碼以及我的數據庫模型。我知道我必須在 postgres 中以某種方式使用 AVG() 函數,但我是 postgres 的新手,所以我非常困惑。主程序package mainimport ("encoding/json""github.com/gorilla/mux""github.com/jinzhu/gorm""github.com/lib/pq""github.com/rs/cors""log""net/http"_ "github.com/jinzhu/gorm/dialects/postgres")type Resource struct { gorm.Model Name string TTS pq.Int64Array `gorm:"type:integer[]"` TTC int}var db *gorm.DBvar err errorfunc main() { router := mux.NewRouter() db, err = gorm.Open( "postgres", "host=localhost"+" user=postgres"+ " dbname=Shoes"+" sslmode=disable password=root") if err != nil { panic("failed to connect database") } defer db.Close() db.AutoMigrate(&Resource{}) router.HandleFunc("/resources", GetResources).Methods("GET") router.HandleFunc("/resources/{id}", GetResource).Methods("GET") router.HandleFunc("/resources", CreateResource).Methods("POST") router.HandleFunc("/resources/{id}", DeleteResource).Methods("DELETE") handler := cors.Default().Handler(router) log.Fatal(http.ListenAndServe(":8080", handler))}func GetResources(w http.ResponseWriter, r *http.Request) { var resources []Resource db.Find(&resources) json.NewEncoder(w).Encode(&resources)}func GetResource(w http.ResponseWriter, r *http.Request) { params := mux.Vars(r) var resource Resource db.First(&resource, params["id"]) json.NewEncoder(w).Encode(&resource)}func CreateResource(w http.ResponseWriter, r *http.Request) { var resource Resource json.NewDecoder(r.Body).Decode(&resource) db.Create(&resource) json.NewEncoder(w).Encode(&resource)}我想我可以做類似的事情db.Select("AVG(tts)")我只是不確定如何將該結果放入列 ttc
1 回答

哈士奇WWW
TA貢獻1799條經驗 獲得超6個贊
由于post請求的json中已經包含了tts_data,可以在設置到數據庫之前取平均值
sum := 0
for _, i := range tts_data {
sum += i
}
avg := sum / len(tts_data)
// save the data in your db
rs := Ressource{Name: "name", TTS: tts_data, ttc: avg}
b := db.Create(&rs)
if b {
// send all the resource
json.NewEncoder(w).Encode(&rs)
// or send only the avg
json.NewEncoder(w).Encode(struct{avg: int}{avg: avg})
} else {
// handle error
}
- 1 回答
- 0 關注
- 121 瀏覽
添加回答
舉報
0/150
提交
取消