Go Gin & Gorm Pagination

Finally get gin gorm pagination,

import (
	"net/http"

	"banners/internal/model"
	"banners/internal/helper"
	"github.com/gin-gonic/gin"
)

func (a *App) IndexBanner(c *gin.Context) {
	
	pagination := helper.Pagination(c)
	var banner model.Banner
	banners, _ := a.PaginationBanners(&banner, &pagination)

	c.JSON(http.StatusOK, gin.H{
		"message": "success",
		"code":    http.StatusOK,
		"data":    banners,
		"status":  true,
	})
}
// app/pagination.go

package app

import (
	"log"

	"banners/internal/model"
)

func (a *App) PaginationBanners(banner *model.Banner, pagination *model.Pagination) (*[]model.Banner, error) {
	var banners []model.Banner

	offset := (pagination.Page - 1) * pagination.Limit

	queryBuilder := a.db.Limit(pagination.Limit).Offset(offset).Order(pagination.Sort)

	result := queryBuilder.Model(&model.Banner{}).Where(banner).Find(&banners)

	if result.Error != nil {
		message := result.Error
		return nil, message
	}

	return &banners, nil
}
// model/pagination.go

package model

type Pagination struct {
	Limit int    `json:"limit`
	Page  int    `json:"page"`
	Sort  string `json:"sort"`
}
// helper/pagination.go


import (
	"strconv"
	"banners/internal/model"
	"github.com/gin-gonic/gin"
)

func Pagination(c *gin.Context) model.Pagination {
	limit := 1
	page := 1
	sort := `created_at DESC`
	query := c.Request.URL.Query()

	for key, value := range query {
		queryValue := value[len(value)-1]
		switch key {
		case "limit":
			limit, _ = strconv.Atoi(queryValue)
			break
		case "page":
			page, _ = strconv.Atoi(queryValue)
			break
		case "sort":
			sort = queryValue
			break
		}
	}

	return model.Pagination{
		Limit: limit,
		Page:  page,
		Sort:  sort,
	}
}

Subscribe to You Live What You Learn

Don’t miss out on the latest issues. Sign up now to get access to the library of members-only issues.
[email protected]
Subscribe