intimate_view/goserver/query_data.go
2020-08-24 19:07:02 +08:00

134 lines
2.3 KiB
Go

package main
import (
"database/sql"
"encoding/json"
"fmt"
"log"
"strconv"
"github.com/gin-gonic/gin"
)
// Query 查询表数据的API 方法
func Query(cxt *gin.Context, platform string) {
var err error
page, err := strconv.Atoi(cxt.Query("page"))
if err != nil {
cxt.Error(err)
return
}
psize, err := strconv.Atoi(cxt.Query("psize"))
if err != nil {
cxt.Error(err)
return
}
if psize > 5000 {
cxt.Error(fmt.Errorf("page size <= 5000"))
return
}
// filter := cxt.Query("filter")
orderfield := cxt.Query("orderfield")
ordertype := cxt.Query("ordertype")
log.Println(orderfield, ordertype)
start := (page - 1) * psize
// end := start + 200
var orderstr string
switch ordertype {
case "ascend":
orderstr = fmt.Sprintf("ORDER BY %s ASC", orderfield)
case "descend":
orderstr = fmt.Sprintf("ORDER BY %s DESC", orderfield)
default:
orderstr = ""
}
ssql := fmt.Sprintf(SqlQuery, platform, orderstr, strconv.Itoa(start), strconv.Itoa(psize))
rows, err := StoreStreamer.Query(ssql)
if err != nil {
cxt.Error(err)
return
}
var ots []*ObjectQuery
for rows.Next() {
ot := &ObjectQuery{}
var views, gratuity sql.NullInt64
var lstm, letm, utm sql.NullTime
var username, tags, livetitle, liveurl sql.NullString
err = rows.Scan(
&ot.Uid,
&ot.Platform,
&ot.UserId,
&username,
&liveurl,
&tags,
&ot.Followers,
&views,
&gratuity,
&livetitle,
&lstm,
&letm,
&utm,
)
if err != nil {
cxt.Error(err)
return
}
if !lstm.Valid {
ot.LiveStartTime = nil
} else {
ot.LiveStartTime = &lstm.Time
}
if !letm.Valid {
ot.LiveEndTime = nil
} else {
ot.LiveEndTime = &letm.Time
}
if !utm.Valid {
ot.UpdateTime = nil
} else {
ot.UpdateTime = &utm.Time
}
if livetitle.Valid {
ot.LiveTitle = livetitle.String
}
if views.Valid {
ot.Views = views.Int64
}
if gratuity.Valid {
ot.Gratuity = gratuity.Int64
}
if username.Valid {
ot.UserName = username.String
}
if liveurl.Valid {
ot.LiveUrl = liveurl.String
}
if err = json.Unmarshal([]byte(tags.String), &ot.Tags); err != nil {
// log.Println(tags)
}
ots = append(ots, ot)
}
r := &Result{Code: 200}
r.Data = ots
// log.Println(len(ots))
if retdata, err := json.Marshal(r); err != nil {
cxt.Error(err)
} else {
cxt.JSON(r.Code, string(retdata))
}
}