最近在写一个Gin和Gorm的项目,里面有用到分页操作,便自己写了一个分页的工具类。

分页请求格式:xxx?page=1&limit=10

utils/Pagination.go

package utils

import (
    "github.com/gin-gonic/gin"
    "github.com/spf13/cast"
    "gorm.io/gorm"
)

type Pagination struct {
    Page   int //页码
    Size   int //每页大小
    Offset int //偏移量
    Total  int //总数
}

// NewPagination 创建分页对象
func NewPagination(c *gin.Context) *Pagination {
    var p = &Pagination{}
    p.Page, p.Size = cast.ToInt(c.Query("page")), cast.ToInt(c.Query("limit"))
    //默认分页
    if p.Page == 0 || p.Size == 0 {
        p.Page, p.Size = 1, 10
    }
    //计算偏移量
    p.Offset = (p.Page - 1) * p.Size
    return p
}

// GormPaginate Gorm分页
func (p *Pagination) GormPaginate() func(db *gorm.DB) *gorm.DB {
    return func(db *gorm.DB) *gorm.DB {
        return db.Offset(p.Offset).Limit(p.Size)
    }
}

controller/UserController.go

package controller

import (
    "github.com/gin-gonic/gin"
    "kakkk-test/service"
    "kakkk-test/utils"
)

func GetUsersHandler(c *gin.Context) {
    p := utils.NewPagination(c)
    service.GetUsersService(c, p)
}

service/UserService.go

package service

import (
    "github.com/gin-gonic/gin"
    "kakkk-test/dao"
    "kakkk-test/utils"
    "net/http"
)

func GetUsersService(c *gin.Context, p *utils.Pagination) {
    users, err := dao.GetUsersByPage(p)
    if err != nil {
        c.JSON(http.StatusOK, gin.H{"err": "DB Error"})
        return
    }
    c.JSON(http.StatusOK, gin.H{
        "page":  p.Page,
        "limit": p.Size,
        "total": p.Total,
        "users": users,
    })
}

dao/UserDao.go

package dao

import (
    "github.com/spf13/cast"
    "gorm.io/gorm"
    "kakkk-test/utils"
)

var DB *gorm.DB

type User struct {
    gorm.Model
    UserName string
    Email    string
    Password string
}

func GetUsersByPage(p *utils.Pagination) (users []User, err error) {
    err = DB.Model(&User{}).Scopes(p.GormPaginate()).Find(&users).Error
    if err != nil {
        return nil, err
    }
    var total int64
    DB.Model(&User{}).Count(&total)
    p.Total = cast.ToInt(total)
    return
}
最后修改:2021 年 09 月 15 日
如果觉得我的文章对你有用,请随意赞赏