GoLang 查询错误:期望切片类型,但得到了结构体类型。

huangapple go评论84阅读模式
英文:

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 (
&quot;encoding/json&quot;
&quot;log&quot;
&quot;net/http&quot;
&quot;time&quot;
_ &quot;github.com/go-sql-driver/mysql&quot;
&quot;github.com/jmoiron/sqlx&quot;
)
type Tag struct {
Stream_count     string `json:&quot;stream_count&quot;`
Query_desc       string `json:&quot;Query_Desc&quot;`
Query_start_date string `json:&quot;Query_start_date&quot;`
Query_end_date   string `json:&quot;Query_end_date&quot;`
Current_date     string `json:&quot;Current_date&quot;`
Error_info       string `json:&quot;Error_Info&quot;`
}
type CachedTag struct {
Tag
expireAtTimeStamp int64
}
var cache = map[string]CachedTag{}
func handler(w http.ResponseWriter, r *http.Request) {
w.Header().Set(&quot;Access-Control-Allow-Origin&quot;, &quot;*&quot;)
w.Header().Set(&quot;Access-Control-Allow-Headers&quot;, &quot;Origin, X-Requested-With, Content-Type, Accept&quot;)
db, err := sqlx.Connect(&quot;mysql&quot;, &quot;*******&quot;)
if err != nil {
log.Print(err.Error())
log.Print(&quot;Error Connecting to DB&quot;)
w.WriteHeader(http.StatusBadRequest)
w.Write([]byte(err.Error()))
return
}
defer db.Close()
date_1 := r.FormValue(&quot;date_1&quot;)
date_2 := r.FormValue(&quot;date_2&quot;)
time_1 := r.FormValue(&quot;time_1&quot;)
time_2 := r.FormValue(&quot;time_2&quot;)
if data, ok := cache[date_1+date_2]; ok {
Now := time.Now().Unix()
if Now &lt; data.expireAtTimeStamp {
j, err := json.Marshal(data.Tag)
log.Print(&quot;Checking Expiry Date&quot;)
if err != nil {
w.WriteHeader(http.StatusBadRequest)
w.Write([]byte((err.Error())))
log.Print(&quot;Caching error&quot;)
return
}
log.Print(&quot;Caching Success&quot;)
w.Write(j)
return
}
}
var tag Tag
err = db.Select(&amp;tag, &quot;SELECT SUM(duration) FROM sessions WHERE (app_id = &#39;*****&#39; OR app_id =&#39;*****&#39; OR app_id =&#39;*****&#39; OR app_id =&#39;*****&#39;OR app_id =&#39;*****&#39;) AND date(created ) between ? and ? and time(created ) between ? and ? AND (`media_src`=&#39;*****&#39; OR `media_src`=&#39;*****&#39; OR `media_src`=&#39;*****&#39; OR `media_src`=&#39;*****&#39;  OR `media_src`=&#39;*****&#39;  OR `media_src`=&#39;*****&#39;) GROUP BY date(created)&quot;, 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 = &quot;Listener Hours&quot;
tag.Query_start_date = date_1
tag.Query_end_date = date_2
dt := time.Now()
tag.Current_date = dt.Format(&quot;01-02-2006 15:04:05&quot;)
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(&quot;/&quot;, handler)
log.Fatal(http.ListenAndServe(&quot;:8081&quot;, 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(&amp;tags, &quot;SELECT ...&quot;)

or you should use

  var tag Tag
err := db.Get(&amp;tag, &quot;SELECT ...&quot;)

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.

huangapple
  • 本文由 发表于 2022年7月12日 18:06:57
  • 转载请务必保留本文链接:https://go.coder-hub.com/72950552.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定