天天看點

go語言分頁 gin架構分頁

 paginate分頁函數封裝

// Paginate 分頁封裝
func Paginate(current int,pageSize int) func(db *gorm.DB) *gorm.DB {
	return func (db *gorm.DB) *gorm.DB {
		if current == 0 {
			current = 1
		}
		switch {
		case pageSize > 100:
			pageSize = 100
		case pageSize <= 0:
			pageSize = 10
		}
		offset := (current - 1) * pageSize
		return db.Offset(offset).Limit(pageSize)
	}
}
           

使用方法

func GetRoleList(query *request.Pagination) (err error, total int64, list []model.Role) {
	db := global.GvaDb.Model(&model.Role{})
	err = db.Where("deleted_at is null").Count(&total).Error
	if err != nil {
		return err, 0, nil
	}
	err = db.Scopes(utils.Paginate(query.Current, query.PageSize)).Order("created_at desc").Find(&list).Error
	return err, total, list
}
           

因為分頁經常會用到,是以這裡推薦将分頁封裝成一個結構體

type Pagination struct {
	Current  int `json:"current" form:"page"`      // 頁碼
	PageSize int `json:"pageSize" form:"pageSize"` // 每頁大小
}