英文:
GoLang Query Error: expected slice but got struct
问题
我对你的代码进行了翻译,如下所示:
package main
import (
"encoding/json"
"log"
"net/http"
"time"
_ "github.com/go-sql-driver/mysql"
"github.com/jmoiron/sqlx"
)
type Tag struct {
Stream_count string `json:"stream_count"`
Query_desc string `json:"Query_Desc"`
Query_start_date string `json:"Query_start_date"`
Query_end_date string `json:"Query_end_date"`
Current_date string `json:"Current_date"`
Error_info string `json:"Error_Info"`
}
type CachedTag struct {
Tag
expireAtTimeStamp int64
}
var cache = map[string]CachedTag{}
func handler(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Access-Control-Allow-Origin", "*")
w.Header().Set("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept")
db, err := sqlx.Connect("mysql", "*******")
if err != nil {
log.Print(err.Error())
log.Print("Error Connecting to DB")
w.WriteHeader(http.StatusBadRequest)
w.Write([]byte(err.Error()))
return
}
defer db.Close()
date_1 := r.FormValue("date_1")
date_2 := r.FormValue("date_2")
time_1 := r.FormValue("time_1")
time_2 := r.FormValue("time_2")
if data, ok := cache[date_1+date_2]; ok {
Now := time.Now().Unix()
if Now < data.expireAtTimeStamp {
j, err := json.Marshal(data.Tag)
log.Print("Checking Expiry Date")
if err != nil {
w.WriteHeader(http.StatusBadRequest)
w.Write([]byte((err.Error())))
log.Print("Caching error")
return
}
log.Print("Caching Success")
w.Write(j)
return
}
}
var tag Tag
err = db.Select(&tag, "SELECT SUM(duration) FROM sessions WHERE (app_id = '*****' OR app_id ='*****' OR app_id ='*****' OR app_id ='*****'OR app_id ='*****') AND date(created ) between ? and ? and time(created ) between ? and ? AND (`media_src`='*****' OR `media_src`='*****' OR `media_src`='*****' OR `media_src`='*****' OR `media_src`='*****' OR `media_src`='*****') GROUP BY date(created)", date_1, date_2, time_1, time_2)
// if err != nil {
// w.WriteHeader(http.StatusBadRequest)
// w.Write([]byte(err.Error()))
// panic(err.Error())
// }
log.Print(tag.Stream_count)
tag.Query_desc = "Listener Hours"
tag.Query_start_date = date_1
tag.Query_end_date = date_2
dt := time.Now()
tag.Current_date = dt.Format("01-02-2006 15:04:05")
if err != nil {
tag.Error_info = err.Error()
}
ct := CachedTag{}
ct.Tag = tag
ct.expireAtTimeStamp = time.Now().Unix() + 1000
cache[date_1+date_2+time_1+time_2] = ct
j, err := json.Marshal(tag)
if err != nil {
w.WriteHeader(http.StatusBadRequest)
w.Write([]byte((err.Error())))
return
}
w.Write(j)
}
func main() {
http.HandleFunc("/", handler)
log.Fatal(http.ListenAndServe(":8081", nil))
}
希望对你有帮助!如果你有任何其他问题,请随时问我。
英文:
I'm fairly new to Golang so i don't know how to change my code to fix this.
Error: expected slice but got struct
Ive looked up slices and researched them i'm just stuck as to how to adjust my struct into a slice and other things that i may need to change.
My Code is below any help would be greatly appreciated
package main
import (
"encoding/json"
"log"
"net/http"
"time"
_ "github.com/go-sql-driver/mysql"
"github.com/jmoiron/sqlx"
)
type Tag struct {
Stream_count string `json:"stream_count"`
Query_desc string `json:"Query_Desc"`
Query_start_date string `json:"Query_start_date"`
Query_end_date string `json:"Query_end_date"`
Current_date string `json:"Current_date"`
Error_info string `json:"Error_Info"`
}
type CachedTag struct {
Tag
expireAtTimeStamp int64
}
var cache = map[string]CachedTag{}
func handler(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Access-Control-Allow-Origin", "*")
w.Header().Set("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept")
db, err := sqlx.Connect("mysql", "*******")
if err != nil {
log.Print(err.Error())
log.Print("Error Connecting to DB")
w.WriteHeader(http.StatusBadRequest)
w.Write([]byte(err.Error()))
return
}
defer db.Close()
date_1 := r.FormValue("date_1")
date_2 := r.FormValue("date_2")
time_1 := r.FormValue("time_1")
time_2 := r.FormValue("time_2")
if data, ok := cache[date_1+date_2]; ok {
Now := time.Now().Unix()
if Now < data.expireAtTimeStamp {
j, err := json.Marshal(data.Tag)
log.Print("Checking Expiry Date")
if err != nil {
w.WriteHeader(http.StatusBadRequest)
w.Write([]byte((err.Error())))
log.Print("Caching error")
return
}
log.Print("Caching Success")
w.Write(j)
return
}
}
var tag Tag
err = db.Select(&tag, "SELECT SUM(duration) FROM sessions WHERE (app_id = '*****' OR app_id ='*****' OR app_id ='*****' OR app_id ='*****'OR app_id ='*****') AND date(created ) between ? and ? and time(created ) between ? and ? AND (`media_src`='*****' OR `media_src`='*****' OR `media_src`='*****' OR `media_src`='*****' OR `media_src`='*****' OR `media_src`='*****') GROUP BY date(created)", date_1, date_2, time_1, time_2)
// if err != nil {
// w.WriteHeader(http.StatusBadRequest)
// w.Write([]byte(err.Error()))
// panic(err.Error())
// }
log.Print(tag.Stream_count)
tag.Query_desc = "Listener Hours"
tag.Query_start_date = date_1
tag.Query_end_date = date_2
dt := time.Now()
tag.Current_date = dt.Format("01-02-2006 15:04:05")
if err != nil {
tag.Error_info = err.Error()
}
ct := CachedTag{}
ct.Tag = tag
ct.expireAtTimeStamp = time.Now().Unix() + 1000
cache[date_1+date_2+time_1+time_2] = ct
j, err := json.Marshal(tag)
if err != nil {
w.WriteHeader(http.StatusBadRequest)
w.Write([]byte((err.Error())))
return
}
w.Write(j)
}
func main() {
http.HandleFunc("/", handler)
log.Fatal(http.ListenAndServe(":8081", nil))
}
答案1
得分: 1
db.Select()返回行,即一个数组(或切片)。
所以你应该使用以下之一:
var tags []Tag
err := db.Select(&tags, "SELECT ...")
或者你可以使用
var tag Tag
err := db.Get(&tag, "SELECT ...")
后者应该用于期望结果中只有0到1行的查询,而select则期望0到N行,并且你必须在返回时检查切片的长度。
英文:
db.Select() returns rows, i.e. an array (or slice).
So you should use either:
var tags []Tag
err := db.Select(&tags, "SELECT ...")
or you should use
var tag Tag
err := db.Get(&tag, "SELECT ...")
The latter should be used for queries expecting only 0..1 rows in the result while select expects 0..N and you must check the length of the slice on return.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论