API處理分頁看似簡單,實際上暗藏危機.最常見的分頁方式,大概是下面這樣的
- 頁數表示法:
/user/?page=1&size=15&name=李 - 偏移量表示法:
/user/?offset=100&limit=15&name=李
使用頁碼表示法對前端開發比較友好,但是本質上是和偏移量表示發相似. 在這里我們將使用 jinzhu/gorm和 gin-gonic/gin 開發一個簡單的分頁介面
分頁查詢URL: http://dev.mojotv.cn:3333/api/ssh-log?client_ip=&page=1&size=10&user_id=0&machine_id=0 回傳json 結果
{
"data": [
{
"id": 28,
"created_at": "2019-09-12T14:25:54+08:00",
"updated_at": "2019-09-12T14:25:54+08:00",
"user_id": 26,
"machine_id": 1,
"ssh_user": "mojotv.cn",
"client_ip": "10.18.60.16",
"started_at": "2019-09-12T14:24:05+08:00",
"status": 0,
"remark": ""
}
],
"ok": true,
"page": 1,
"size": 10,
"total": 1
}
復制代碼
1. 定義分頁struct
//PaginationQ gin handler query binding struct
type PaginationQ struct {
Ok bool `json:"ok"`
Size uint `form:"size" json:"size"`
Page uint `form:"page" json:"page"`
Data interface{} `json:"data" comment:"muster be a pointer of slice gorm.Model"` // save pagination list
Total uint `json:"total"`
}
復制代碼
Ok代表業務查詢沒有出錯Size每頁顯示的數量,使用formtag 接受gin的url-query引數Page當前頁碼,使用formtag 接受gin的url-query引數Data分頁的資料內容Total全部的頁碼數量
2. 資料表Model
這里以ssh_log(ssh 命令日志為示例),使用GORM創建MYSQL資料表模型, 使用 form tag 接受gin的url-query引數,作為搜索條件
type SshLog struct {
BaseModel
UserId uint `gorm:"index" json:"user_id" form:"user_id"` //form tag 系結gin url-query 引數
MachineId uint `gorm:"index" json:"machine_id" form:"machine_id"` //form tag 系結gin url-query 引數
SshUser string `json:"ssh_user" comment:"ssh賬號"`
ClientIp string `json:"client_ip" form:"client_ip"` //form tag 系結gin url-query 引數
StartedAt time.Time `json:"started_at" form:"started_at"`
Status uint `json:"status" comment:"0-未標記 2-正常 4-警告 8-危險 16-致命"`
Remark string `json:"remark"`
Log string `gorm:"type:text" json:"log"`
Machine Machine `gorm:"association_autoupdate:false;association_autocreate:false" json:"machine"`
User User `gorm:"association_autoupdate:false;association_autocreate:false" json:"user"`
}
復制代碼

3. 定義分頁查詢搜索的結構體
ssh2ws/internal/h_ssh_log.go
type SshLogQ struct {
SshLog
PaginationQ
FromTime string `form:"from_time"` //搜索開始時間
ToTime string `form:"to_time"` //搜索結束時候
}
復制代碼
這個結構體是提供給gin handler用作引數系結的. 使用的方法如下:
func SshLogAll(c *gin.Context) {
query := &model.SshLogQ{}
err := c.ShouldBindQuery(query) //開始系結url-query 引數到結構體
if handleError(c, err) {
return
}
list, total, err := query.Search() //開始mysql 業務搜索查詢
if handleError(c, err) {
return
}
//回傳資料開始拼裝分頁json
jsonPagination(c, list, total, &query.PaginationQ)
}
復制代碼
4. 分頁和搜索資料查詢
- 1.創建 db-query
- 2.搜索非空業務欄位
- 3.使用crudAll 方法獲取資料
model/m_ssh_log.go
type SshLogQ struct {
SshLog
PaginationQ
FromTime string `form:"from_time"`
ToTime string `form:"to_time"`
}
func (m SshLogQ) Search() (list *[]SshLog, total uint, err error) {
list = &[]SshLog{}
//創建 db-query
tx := db.Model(m.SshLog).Preload("User").Preload("Machine")
//搜索非空業務欄位
if m.ClientIp != "" {
tx = tx.Where("client_ip like ?", "%"+m.ClientIp+"%")
}
//搜索時間段
if m.FromTime != "" && m.ToTime != "" {
tx = tx.Where("`created_at` BETWEEN ? AND ?", m.FromTime, m.ToTime)
}
//使用crudAll 方法獲取資料
total, err = crudAll(&m.PaginationQ, tx, list)
return
}
復制代碼
crudAll 方法來構建sql分頁資料,
-
設定默認引數
-
獲取全部搜索數量
-
獲取偏移量的資料
-
拼裝json 分頁資料
model/helper.go
func crudAll(p *PaginationQ, queryTx *gorm.DB, list interface{}) (uint, error) {
//1.默認引數
if p.Size < 1 {
p.Size = 10
}
if p.Page < 1 {
p.Page = 1
}
//2.部搜索數量
var total uint err := queryTx.Count(&total).Error if err != nil {
return 0, err
}
offset := p.Size * (p.Page - 1)
//3.偏移量的資料
err = queryTx.Limit(p.Size).Offset(offset).Find(list).Error if err != nil {
return 0, err
}
return total, err
}
//4.json 分頁資料
func jsonPagination(c *gin.Context, list interface{}, total uint, query *model.PaginationQ) {
c.AbortWithStatusJSON(200, gin.H{
“ok”: true,
“data”: list,
“total”: total,
“page”: query.Page,
“size”: query.Size
})
}
復制代碼
API處理分頁看似簡單,實際上暗藏危機.最常見的分頁方式,大概是下面這樣的
- 頁數表示法:
/user/?page=1&size=15&name=李 - 偏移量表示法:
/user/?offset=100&limit=15&name=李
使用頁碼表示法對前端開發比較友好,但是本質上是和偏移量表示發相似. 在這里我們將使用 jinzhu/gorm和 gin-gonic/gin 開發一個簡單的分頁介面
分頁查詢URL: http://dev.mojotv.cn:3333/api/ssh-log?client_ip=&page=1&size=10&user_id=0&machine_id=0 回傳json 結果
{
"data": [
{
"id": 28,
"created_at": "2019-09-12T14:25:54+08:00",
"updated_at": "2019-09-12T14:25:54+08:00",
"user_id": 26,
"machine_id": 1,
"ssh_user": "mojotv.cn",
"client_ip": "10.18.60.16",
"started_at": "2019-09-12T14:24:05+08:00",
"status": 0,
"remark": ""
}
],
"ok": true,
"page": 1,
"size": 10,
"total": 1
}
復制代碼
5.例子代碼
完整專案代碼地址
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/350772.html
標籤:其他
下一篇:【面試】北京Python后端開發
