Categorygithub.com/dotdevgo/gorm-paginator
repositorypackage
0.2.0
Repository: https://github.com/dotdevgo/gorm-paginator.git
Documentation: pkg.go.dev

# Packages

No description provided by the author

# README

gorm-paginator

Build Status codecov Go Report Card GoDoc

A simple paginator for gorm. Also supports direct pagination via http.Request query parameters.

Installation

go get -u github.com/dotdevgo/gorm-paginator

Usage

Basic usage

package main

import (
	"fmt"

	"github.com/jinzhu/gorm"
	_ "github.com/jinzhu/gorm/dialects/mysql"
	paginator "github.com/dotdevgo/gorm-paginator"
)

type model struct {
	gorm.Model
	Name string
}

func main() {
	db, err := gorm.Open("mysql", "root:root@tcp(mysql)/db?parseTime=true")
	if err != nil {
		panic(err)
	}

	var m []model

	options := []paginator.Option{
		paginator.WithPage(2),
		paginator.WithLimit(10),
		paginator.WithOrder("name DESC"),
	}

	res, err := paginator.Paginate(db, &m, options...)
	if err != nil {
		panic(err)
	}

	fmt.Printf("TotalRecords:   %d\n", res.TotalRecords)
	fmt.Printf("CurrentPage:    %d\n", res.CurrentPage)
	fmt.Printf("MaxPage:        %d\n", res.MaxPage)
	fmt.Printf("RecordsPerPage: %d\n", res.RecordsPerPage)
	fmt.Printf("IsFirstPage?:   %v\n", res.IsFirstPage())
	fmt.Printf("IsLastPage?:    %v\n", res.IsLastPage())

	for _, record := range res.Records.([]model) {
		fmt.Printf("ID:   %d", record.ID)
		fmt.Printf("Name: %s", record.Name)
	}
}

Pagination via http.Request query params

package main

import (
	"encoding/json"
	"net/http"

	"github.com/jinzhu/gorm"
	_ "github.com/jinzhu/gorm/dialects/mysql"
	paginator "github.com/dotdevgo/gorm-paginator"
)

type model struct {
	gorm.Model
	Name string
}

func main() {
	db, err := gorm.Open("mysql", "root:root@tcp(mysql)/db?parseTime=true")
	if err != nil {
		panic(err)
	}

	// Example pagination request: /model?page=2&order=name+DESC&limit=10
	//
	// Check the godoc for paginator.WithRequest and paginator.ParamNames to
	// see how to configure the parameter names.
	http.Handle("/model", http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		var m []model

		res, err := paginator.Paginate(db, &m, paginator.WithRequest(r))
		if err != nil {
			w.WriteHeader(http.StatusInternalServerError)
			json.NewEncoder(w).Encode(map[string]string{"error": err.Error()})
			return
		}

		json.NewEncoder(w).Encode(res)
	}))

	http.ListenAndServe(":8080", nil)
}

License

The source code of gorm-paginator is released under the MIT License. See the bundled LICENSE file for details.