gorm+gin實(shí)現(xiàn)restful分頁接口的實(shí)踐
API處理分頁看似簡單,實(shí)際上暗藏危機(jī).最常見的分頁方式,大概是下面這樣的
- 頁數(shù)表示法:/user/?page=1&size=15&name=李
- 偏移量表示法:/user/?offset=100&limit=15&name=李
使用頁碼表示法對(duì)前端開發(fā)比較友好,但是本質(zhì)上是和偏移量表示發(fā)相似. 在這里我們將使用?jinzhu/gorm和?gin-gonic/gin?開發(fā)一個(gè)簡單的分頁接口
分頁查詢URL:?http://dev.mojotv.cn:3333/api/ssh-log?client_ip=&page=1&size=10&user_id=0&machine_id=0?返回json 結(jié)果
{
"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?代表業(yè)務(wù)查詢沒有出錯(cuò)
- Size?每頁顯示的數(shù)量,使用?form?tag 接受gin的url-query參數(shù)
- Page?當(dāng)前頁碼,使用?form?tag 接受gin的url-query參數(shù)
- Data?分頁的數(shù)據(jù)內(nèi)容
- Total?全部的頁碼數(shù)量
2. 數(shù)據(jù)表Model
這里以ssh_log(ssh 命令日志為示例),使用GORM創(chuàng)建MYSQL數(shù)據(jù)表模型, 使用?form?tag 接受gin的url-query參數(shù),作為搜索條件
type SshLog struct {
BaseModel
UserId uint `gorm:"index" json:"user_id" form:"user_id"` //form tag 綁定gin url-query 參數(shù)
MachineId uint `gorm:"index" json:"machine_id" form:"machine_id"` //form tag 綁定gin url-query 參數(shù)
SshUser string `json:"ssh_user" comment:"ssh賬號(hào)"`
ClientIp string `json:"client_ip" form:"client_ip"` //form tag 綁定gin url-query 參數(shù)
StartedAt time.Time `json:"started_at" form:"started_at"`
Status uint `json:"status" comment:"0-未標(biāo)記 2-正常 4-警告 8-危險(xiǎn) 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. 定義分頁查詢搜索的結(jié)構(gòu)體
ssh2ws/internal/h_ssh_log.go
type SshLogQ struct {
SshLog
PaginationQ
FromTime string `form:"from_time"` //搜索開始時(shí)間
ToTime string `form:"to_time"` //搜索結(jié)束時(shí)候
}
這個(gè)結(jié)構(gòu)體是提供給gin handler用作參數(shù)綁定的. 使用的方法如下:
func SshLogAll(c *gin.Context) {
query := &model.SshLogQ{}
err := c.ShouldBindQuery(query) //開始綁定url-query 參數(shù)到結(jié)構(gòu)體
if handleError(c, err) {
return
}
list, total, err := query.Search() //開始mysql 業(yè)務(wù)搜索查詢
if handleError(c, err) {
return
}
//返回?cái)?shù)據(jù)開始拼裝分頁json
jsonPagination(c, list, total, &query.PaginationQ)
}
4. 分頁和搜索數(shù)據(jù)查詢
1.創(chuàng)建 db-query
2.搜索非空業(yè)務(wù)字段
3.使用crudAll 方法獲取數(shù)據(jù)
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{}
//創(chuàng)建 db-query
tx := db.Model(m.SshLog).Preload("User").Preload("Machine")
//搜索非空業(yè)務(wù)字段
if m.ClientIp != "" {
tx = tx.Where("client_ip like ?", "%"+m.ClientIp+"%")
}
//搜索時(shí)間段
if m.FromTime != "" && m.ToTime != "" {
tx = tx.Where("`created_at` BETWEEN ? AND ?", m.FromTime, m.ToTime)
}
//使用crudAll 方法獲取數(shù)據(jù)
total, err = crudAll(&m.PaginationQ, tx, list)
return
}
crudAll 方法來構(gòu)建sql分頁數(shù)據(jù),
- 設(shè)置默認(rèn)參數(shù)
- 獲取全部搜索數(shù)量
- 獲取偏移量的數(shù)據(jù)
- 拼裝json 分頁數(shù)據(jù)?
model/helper.go
func crudAll(p *PaginationQ, queryTx *gorm.DB, list interface{}) (uint, error) {
//1.默認(rèn)參數(shù)
if p.Size < 1 {
p.Size = 10
}
if p.Page < 1 {
p.Page = 1
}
//2.部搜索數(shù)量
var total uint err := queryTx.Count(&total).Error if err != nil {
return 0, err
}
offset := p.Size * (p.Page - 1)
//3.偏移量的數(shù)據(jù)
err = queryTx.Limit(p.Size).Offset(offset).Find(list).Error if err != nil {
return 0, err
}
return total, err
}
//4.json 分頁數(shù)據(jù)
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處理分頁看似簡單,實(shí)際上暗藏危機(jī).最常見的分頁方式,大概是下面這樣的
- 頁數(shù)表示法:/user/?page=1&size=15&name=李
- 偏移量表示法:/user/?offset=100&limit=15&name=李
使用頁碼表示法對(duì)前端開發(fā)比較友好,但是本質(zhì)上是和偏移量表示發(fā)相似. 在這里我們將使用?jinzhu/gorm和?gin-gonic/gin?開發(fā)一個(gè)簡單的分頁接口
分頁查詢URL:?http://dev.mojotv.cn:3333/api/ssh-log?client_ip=&page=1&size=10&user_id=0&machine_id=0?返回json 結(jié)果
{
"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.例子代碼
到此這篇關(guān)于gorm+gin實(shí)現(xiàn)restful分頁接口的實(shí)踐的文章就介紹到這了,更多相關(guān)gorm gin restful分頁接口內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
使用Go語言編寫一個(gè)毫秒級(jí)生成組件庫文檔工具
在開發(fā)組件庫的過程中,文檔無疑是不可或缺的一環(huán),在本文中將嘗試將Go語言與前端技術(shù)巧妙融合,以創(chuàng)建一款能在毫秒級(jí)別完成文檔生成的工具,需要的可以參考下2024-03-03
go 原生http web 服務(wù)跨域restful api的寫法介紹
這篇文章主要介紹了go 原生http web 服務(wù)跨域restful api的寫法,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過來看看吧2021-04-04
Golang使用Gin創(chuàng)建Restful API的實(shí)現(xiàn)
本文主要介紹了Golang使用Gin創(chuàng)建Restful API的實(shí)現(xiàn),文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2023-01-01
利用Go語言快速實(shí)現(xiàn)一個(gè)極簡任務(wù)調(diào)度系統(tǒng)
任務(wù)調(diào)度(Task Scheduling)是很多軟件系統(tǒng)中的重要組成部分,字面上的意思是按照一定要求分配運(yùn)行一些通常時(shí)間較長的腳本或程序。本文將利用Go語言快速實(shí)現(xiàn)一個(gè)極簡任務(wù)調(diào)度系統(tǒng),感興趣的可以了解一下2022-10-10
淺析Go語言如何在select語句中實(shí)現(xiàn)優(yōu)先級(jí)
這篇文章主要為大家詳細(xì)介紹了Go語言如何在select語句中實(shí)現(xiàn)優(yōu)先級(jí),文中的示例代碼講解詳細(xì),感興趣的小伙伴可以跟隨小編一起學(xué)習(xí)一下2024-03-03

