咔叽游戏

 找回密码
 立即注册

QQ登录

只需一步,快速开始

搜索
查看: 758|回复: 0

[Golang] gorm+gin实现restful分页接口的实践

[复制链接]
  • TA的每日心情
    无聊
    2019-5-27 08:20
  • 签到天数: 4 天

    [LV.2]圆转纯熟

    发表于 2022-1-10 11:12:12 | 显示全部楼层 |阅读模式
    目录

      1. 定义分页struct2. 数据表Model3. 定义分页查询搜索的结构体4. 分页和搜索数据查询5.例子代码

    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 结果
    1. {
    2.     "data": [
    3.         {
    4.             "id": 28,
    5.             "created_at": "2019-09-12T14:25:54+08:00",
    6.             "updated_at": "2019-09-12T14:25:54+08:00",
    7.             "user_id": 26,
    8.             "machine_id": 1,
    9.             "ssh_user": "mojotv.cn",
    10.             "client_ip": "10.18.60.16",
    11.             "started_at": "2019-09-12T14:24:05+08:00",
    12.             "status": 0,
    13.             "remark": ""
    14.         }
    15.     ],
    16.     "ok": true,
    17.     "page": 1,
    18.     "size": 10,
    19.     "total": 1
    20. }
    复制代码
    1. 定义分页struct

    1. //PaginationQ gin handler query binding struct
    2. type PaginationQ struct {
    3. Ok    bool        `json:"ok"`
    4. Size  uint        `form:"size" json:"size"`
    5. Page  uint        `form:"page" json:"page"`
    6. Data  interface{} `json:"data" comment:"muster be a pointer of slice gorm.Model"` // save pagination list
    7. Total uint        `json:"total"`
    8. }
    复制代码
      Ok代表业务查询没有出错Size每页显示的数量,使用formtag 接受gin的url-query参数Page当前页码,使用formtag 接受gin的url-query参数Data分页的数据内容Total全部的页码数量

    2. 数据表Model


    这里以ssh_log(ssh 命令日志为示例),使用GORM创建MYSQL数据表模型, 使用formtag 接受gin的url-query参数,作为搜索条件
    1. type SshLog struct {
    2. BaseModel
    3. UserId    uint      `gorm:"index" json:"user_id" form:"user_id"` //form tag 绑定gin url-query 参数
    4. MachineId uint      `gorm:"index" json:"machine_id" form:"machine_id"` //form tag 绑定gin url-query 参数
    5. SshUser   string    `json:"ssh_user" comment:"ssh账号"`
    6. ClientIp  string    `json:"client_ip" form:"client_ip"` //form tag 绑定gin url-query 参数
    7. StartedAt time.Time `json:"started_at" form:"started_at"`
    8. Status    uint      `json:"status" comment:"0-未标记 2-正常 4-警告 8-危险 16-致命"`
    9. Remark    string    `json:"remark"`
    10. Log       string    `gorm:"type:text" json:"log"`
    11. Machine   Machine   `gorm:"association_autoupdate:false;association_autocreate:false" json:"machine"`
    12. User      User      `gorm:"association_autoupdate:false;association_autocreate:false" json:"user"`
    13. }
    复制代码
    gorm+gin实现restful分页接口的实践-1.jpg


    3. 定义分页查询搜索的结构体

    1. ssh2ws/internal/h_ssh_log.go
    2. type SshLogQ struct {
    3. SshLog
    4. PaginationQ
    5. FromTime string `form:"from_time"` //搜索开始时间
    6. ToTime   string `form:"to_time"`  //搜索结束时候
    7. }
    复制代码
    这个结构体是提供给gin handler用作参数绑定的. 使用的方法如下:
    1. func SshLogAll(c *gin.Context) {
    2. query := &model.SshLogQ{}
    3. err := c.ShouldBindQuery(query) //开始绑定url-query 参数到结构体
    4. if handleError(c, err) {
    5.   return
    6. }
    7. list, total, err := query.Search()  //开始mysql 业务搜索查询
    8. if handleError(c, err) {
    9.   return
    10. }
    11. //返回数据开始拼装分页json
    12. jsonPagination(c, list, total, &query.PaginationQ)
    13. }
    复制代码
    4. 分页和搜索数据查询

    1.创建 db-query
    2.搜索非空业务字段
    3.使用crudAll 方法获取数据
    1. model/m_ssh_log.go
    2. type SshLogQ struct {
    3. SshLog
    4. PaginationQ
    5. FromTime string `form:"from_time"`
    6. ToTime   string `form:"to_time"`
    7. }
    8. func (m SshLogQ) Search() (list *[]SshLog, total uint, err error) {
    9. list = &[]SshLog{}
    10. //创建 db-query
    11. tx := db.Model(m.SshLog).Preload("User").Preload("Machine")
    12. //搜索非空业务字段
    13. if m.ClientIp != "" {
    14.   tx = tx.Where("client_ip like ?", "%"+m.ClientIp+"%")
    15. }
    16. //搜索时间段
    17. if m.FromTime != "" && m.ToTime != "" {
    18.   tx = tx.Where("`created_at` BETWEEN ? AND ?", m.FromTime, m.ToTime)
    19. }
    20. //使用crudAll 方法获取数据
    21. total, err = crudAll(&m.PaginationQ, tx, list)
    22. return
    23. }
    复制代码
    crudAll 方法来构建sql分页数据,
      设置默认参数获取全部搜索数量获取偏移量的数据拼装json 分页数据
    model/helper.go
    1. func crudAll(p *PaginationQ, queryTx *gorm.DB, list interface{}) (uint, error) {
    2.     //1.默认参数
    3.     if p.Size < 1 {
    4.         p.Size = 10
    5.     }
    6.     if p.Page < 1 {
    7.         p.Page = 1
    8.     }
    9.     //2.部搜索数量
    10.     var total uint err := queryTx.Count(&total).Error if err != nil {
    11.         return 0, err
    12.     }
    13.     offset := p.Size * (p.Page - 1)
    14.     //3.偏移量的数据
    15.     err = queryTx.Limit(p.Size).Offset(offset).Find(list).Error if err != nil {
    16.         return 0, err
    17.     }
    18.     return total, err
    19. }
    20. //4.json 分页数据
    21. func jsonPagination(c *gin.Context, list interface{}, total uint, query *model.PaginationQ) {
    22.     c.AbortWithStatusJSON(200, gin.H{
    23.         “ok”: true,
    24.         “data”: list,
    25.         “total”: total,
    26.         “page”: query.Page,
    27.         “size”: query.Size
    28.     })
    29. }
    复制代码
    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 结果
    1. {
    2.     "data": [
    3.         {
    4.             "id": 28,
    5.             "created_at": "2019-09-12T14:25:54+08:00",
    6.             "updated_at": "2019-09-12T14:25:54+08:00",
    7.             "user_id": 26,
    8.             "machine_id": 1,
    9.             "ssh_user": "mojotv.cn",
    10.             "client_ip": "10.18.60.16",
    11.             "started_at": "2019-09-12T14:24:05+08:00",
    12.             "status": 0,
    13.             "remark": ""
    14.         }
    15.     ],
    16.     "ok": true,
    17.     "page": 1,
    18.     "size": 10,
    19.     "total": 1
    20. }
    复制代码
    5.例子代码


    完整项目代码地址
    到此这篇关于gorm+gin实现restful分页接口的实践的文章就介绍到这了,更多相关gorm gin restful分页接口内容请搜索咔叽论坛以前的文章或继续浏览下面的相关文章希望大家以后多多支持咔叽论坛!

    原文地址:https://www.jb51.net/article/232578.htm

    QQ|免责声明|小黑屋|手机版|Archiver|咔叽游戏

    GMT+8, 2024-3-29 09:00

    Powered by Discuz! X3.4

    © 2001-2023 Discuz! Team.

    快速回复 返回顶部 返回列表