89 lines
2.5 KiB
Go
89 lines
2.5 KiB
Go
package models
|
|
|
|
import (
|
|
"encoding/json"
|
|
"log"
|
|
"net/http"
|
|
)
|
|
|
|
type ListView struct {
|
|
Page int `json:"page"`
|
|
PageSize int `json:"page_size"`
|
|
Total int64 `json:"total"`
|
|
Next bool `json:"next"`
|
|
List []interface{} `json:"list"`
|
|
Type string `json:"-"`
|
|
}
|
|
|
|
// 轉換爲JSON並返回
|
|
func (listview *ListView) ToJSON() []byte {
|
|
if listview.List == nil {
|
|
listview.List = make([]interface{}, 0)
|
|
}
|
|
b, err := json.MarshalIndent(listview, "", " ")
|
|
if err != nil {
|
|
log.Println(err)
|
|
return nil
|
|
}
|
|
return b
|
|
}
|
|
|
|
//func (listview *ListView) Readx(r *http.Request, model interface{}, list interface{}) error {
|
|
// listview.Page = utils.ParamInt(r.URL.Query().Get("page"), 1)
|
|
// listview.PageSize = utils.ParamInt(r.URL.Query().Get("pageSize"), 10)
|
|
// db := configs.ORMDB()
|
|
// db.Model(&model).Offset((listview.Page - 1) * listview.PageSize).Limit(listview.PageSize).Find(&list)
|
|
// db.Model(&model).Count(&listview.Total)
|
|
// listview.Next = listview.Page*listview.PageSize < int(listview.Total)
|
|
// listview.List = list.([]interface{})
|
|
// return nil
|
|
//}
|
|
//
|
|
//func (listview *ListView) Read(r *http.Request) error {
|
|
// listview.Page = utils.ParamInt(r.URL.Query().Get("page"), 1)
|
|
// listview.PageSize = utils.ParamInt(r.URL.Query().Get("pageSize"), 10)
|
|
//
|
|
// db := configs.ORMDB()
|
|
//
|
|
// // 按照 user_id 篩選
|
|
// if user_id := utils.ParamInt(r.URL.Query().Get("user_id"), 0); user_id > 0 {
|
|
// db = db.Where("user_id = ?", user_id)
|
|
// }
|
|
//
|
|
// // 按照 star 篩選
|
|
// if star := utils.ParamInt(r.URL.Query().Get("star"), 0); star > 0 {
|
|
// db = db.Where("stars LIKE ?", "%"+strconv.Itoa(star)+"%")
|
|
// }
|
|
//
|
|
// // 按照 name 模糊搜索
|
|
// if name := r.URL.Query().Get("name"); name != "" {
|
|
// db = db.Where("name LIKE ?", "%"+name+"%")
|
|
// }
|
|
//
|
|
// // 按照 type 篩選
|
|
// if model_type := r.URL.Query().Get("type"); model_type != "" {
|
|
// db = db.Where("type = ?", model_type)
|
|
// }
|
|
//
|
|
// // 按照 status 篩選
|
|
// if status := r.URL.Query().Get("status"); status != "" {
|
|
// db = db.Where("status = ?", status)
|
|
// }
|
|
//
|
|
// // 按照 tag 篩選
|
|
// if tag := r.URL.Query().Get("tag"); tag != "" {
|
|
// db = db.Where("tags LIKE ?", "%"+tag+"%")
|
|
// }
|
|
//
|
|
// db.Offset((listview.Page - 1) * listview.PageSize).Limit(listview.PageSize).Find(&listview.List)
|
|
// db.Model(listview.List).Count(&listview.Total)
|
|
//
|
|
// return nil
|
|
//}
|
|
|
|
// 直接輸出JSON給瀏覽器
|
|
func (listview *ListView) WriteJSON(w http.ResponseWriter) {
|
|
w.Header().Set("Content-Type", "application/json; charset=utf-8")
|
|
w.Write(listview.ToJSON())
|
|
}
|