pager

package module
v0.0.0-...-b6d1c84 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Sep 30, 2020 License: MIT Imports: 5 Imported by: 1

README

pager build

Pager is a web paging tool for golang

Interface

This tool provides gorm-based data paging. If you don't need Gorm, you can choose to implement the following interface or create issues.

type Driver interface {
	Where(kv Where)
	Range(r Range)
	Limit(limit int)
	Skip(skip int)
	Index(index string)
	Sort(kv []SortInfo)
	Find(data interface{})
	SetTyp(typ reflect.Type)
	Count() int64
}

Url-rule

Run the sample code to see the effect

example

package main

import (
	"encoding/json"
	"github.com/kenretto/pager"
	"github.com/kenretto/pager/driver"
	"gorm.io/driver/sqlite"
	"gorm.io/gorm"
	"gorm.io/gorm/logger"
	"log"
	"net/http"
	"os"
	"time"
)

type user struct {
	gorm.Model
	Nickname string `json:"nickname" gorm:"column:nickname;type:varchar(16)"`
	Age      uint8  `json:"age" gorm:"column:age;"`
}

// TableName table name
func (user) TableName() string {
	return "members"
}

var u user

var users = []user{
	{Nickname: "a", Age: 1},
	{Nickname: "b", Age: 2},
	{Nickname: "c", Age: 3},
	{Nickname: "d", Age: 4},
	{Nickname: "e", Age: 5},
	{Nickname: "f", Age: 6},
	{Nickname: "g", Age: 7},
	{Nickname: "h", Age: 8},
	{Nickname: "i", Age: 9},
	{Nickname: "j", Age: 10},
	{Nickname: "k", Age: 11},
	{Nickname: "l", Age: 12},
	{Nickname: "m", Age: 13},
	{Nickname: "n", Age: 14},
	{Nickname: "o", Age: 15},
	{Nickname: "p", Age: 16},
	{Nickname: "q", Age: 17},
	{Nickname: "r", Age: 18},
	{Nickname: "s", Age: 19},
	{Nickname: "t", Age: 20},
	{Nickname: "u", Age: 21},
	{Nickname: "v", Age: 22},
	{Nickname: "w", Age: 23},
	{Nickname: "x", Age: 24},
	{Nickname: "y", Age: 25},
	{Nickname: "z", Age: 26},
}

func main() {
	var db, err = gorm.Open(sqlite.Open("file:pager?mode=memory&cache=shared&_fk=1"), &gorm.Config{PrepareStmt: true, Logger: logger.New(
		log.New(os.Stdout, "\r\n", log.LstdFlags), // io writer
		logger.Config{
			SlowThreshold: time.Second,
			LogLevel:      logger.Info,
			Colorful:      false,
		},
	)})
	if err != nil {
		log.Fatalln(err)
	}
	_ = db.AutoMigrate(&u)
	db.Model(&u).Create(&users)

	http.HandleFunc("/member", func(writer http.ResponseWriter, request *http.Request) {
		writer.Header().Set("Content-Type", "application/json")
		data, _ := json.Marshal(pager.New(request, driver.NewGormDriver(db)).
			SetPaginationField("ID").SetIndex(u.TableName()).
			Find(u).Result())
		_, _ = writer.Write(data)
	})
	log.Fatalln(http.ListenAndServe(":3359", nil))
}

Documentation

Overview

Package pager Paging tool

pager.New(ctx, driver).SetIndex(c.entity.TableName()).Find(c.entity).Result()

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func ParseSkip

func ParseSkip(request *http.Request) int

ParseSkip Number of rows skipped

func StringToBool

func StringToBool(val interface{}) interface{}

StringToBool convert string to bool

func StringToFloat32

func StringToFloat32(val interface{}) interface{}

StringToFloat32 convert string to float32

In fact, if the string type data is not passed in, then the int32 type data will not be returned here, but the original data will be returned.

func StringToFloat64

func StringToFloat64(val interface{}) interface{}

StringToFloat64 convert string to float64

In fact, if the string type data is not passed in, then the float64 type data will not be returned here, but the original data will be returned.

func StringToInt

func StringToInt(val interface{}) interface{}

StringToInt convert string to int

In fact, if the string type data is not passed in, then the int type data will not be returned here, but the original data will be returned.

Types

type Driver

type Driver interface {
	// Set filter conditions
	Where(kv Where)
	// Set range query conditions
	Range(r Range)
	// Set the limit per page
	Limit(limit int)
	// Set the number of skips
	Skip(skip int)
	// Index Index name, which can be a table name, or, for example, the index name of es, something that identifies a specific collection of resources
	Index(index string)
	// 排序
	Sort(kv []SortInfo)
	// Query operation, driver, it is recommended to perform real data scanning in this method to save performance
	Find(data interface{})
	// If the data structure passed by the Find method needs to be analyzed in the implementation code of the specific driver,
	// this method will be called and passed in the data reflection type. For example, in mongo,
	// the construction of the query language has strict requirements on the type. Here,
	// the reflection Type of the data type will be passed in to drive the driver to analyze the record data type and convert the filtered data passed in by Where.
	SetTyp(typ reflect.Type)
	// Calculate the total number of qualified data items according to all filter conditions
	Count() int64
}

Driver Data query driver, Pagination will pass the parsed parameters to it. Theoretically, any driver that implements this interface can call this package to achieve the general paging function.

type FilterKey

type FilterKey struct {
	// page parameter name
	Page string
	// rows parameter name
	Rows string
	// sorts parameter name
	Sorts string
	// range parameter name
	Range string
}

FilterKey Custom name of the parameter carried by url

type Int64Slice

type Int64Slice []int64

Int64Slice int64 sort

func (Int64Slice) Len

func (p Int64Slice) Len() int

func (Int64Slice) Less

func (p Int64Slice) Less(i, j int) bool

func (Int64Slice) Swap

func (p Int64Slice) Swap(i, j int)

type Pagination

type Pagination struct {
	// contains filtered or unexported fields
}

Pagination page tool

func New

func New(request *http.Request, driver Driver) *Pagination

New instance

func (*Pagination) AddDisableField

func (pagination *Pagination) AddDisableField(fields ...string) *Pagination

AddDisableField add fields that are prohibited from participating in search filtering

func (*Pagination) AddFilterKeyMapping

func (pagination *Pagination) AddFilterKeyMapping(key, column string) *Pagination

AddFilterKeyMapping filter condition mapping. If the key carried by url is different from the field name of the database, set it here

func (*Pagination) Find

func (pagination *Pagination) Find(structure interface{}) *Pagination

Find use driver to query data

structure the structure of the data, without the need for a pointer

func (*Pagination) Limit

func (pagination *Pagination) Limit(limit int) *Pagination

Limit set the default number of data items returned per page

func (*Pagination) ParseRange

func (pagination *Pagination) ParseRange() Range

ParseRange range

func (*Pagination) ParsingLimit

func (pagination *Pagination) ParsingLimit() int

ParsingLimit Parse the number of entries displayed per page from the http request

func (*Pagination) ParsingQuery

func (pagination *Pagination) ParsingQuery() Where

ParsingQuery Parse the filter condition from the http request

func (*Pagination) Range

func (pagination *Pagination) Range(r Range) *Pagination

Range specify range query parameters

func (*Pagination) Result

func (pagination *Pagination) Result() *Result

Result get result

func (*Pagination) SetFilterKey

func (pagination *Pagination) SetFilterKey(key FilterKey) *Pagination

SetFilterKey custom paging related query parameters

func (*Pagination) SetIndex

func (pagination *Pagination) SetIndex(index string) *Pagination

SetIndex set the collection or table name in the query driver, for example, the database is the table name

func (*Pagination) SetPaginationField

func (pagination *Pagination) SetPaginationField(field string) *Pagination

SetPaginationField when this value is set, the next_id in the returned data will be equal to the field value of the last element in slice, and prev_id will be equal to the field value of the first element in slice

func (*Pagination) Sort

func (pagination *Pagination) Sort(kv []SortInfo) *Pagination

Sort specify sort

func (*Pagination) Where

func (pagination *Pagination) Where(kv Where) *Pagination

Where set default query parameters, such as returning only the user's own browsing log after the user logs in, which is valid throughout the life cycle of the object.

type Range

type Range map[RangeKey]map[RangeType]int64

Range Built range query parameters

func (Range) Add

func (r Range) Add(key RangeKey, typ RangeType, val int64)

Add add

func (Range) Parse

func (r Range) Parse(request *http.Request)

Parse parse

type RangeKey

type RangeKey string

RangeKey Data field

type RangeType

type RangeType int

RangeType Types

Gte: Greater than or equal to
Lte: Less than or equal to
const (
	// Gte Greater than or equal to
	Gte RangeType = iota
	// Lte Less than or equal to
	Lte
)

func (RangeType) String

func (s RangeType) String() string

type Result

type Result struct {
	Data   interface{} `json:"data" xml:"data"`       // data slice
	NextID interface{} `json:"next_id" xml:"next_id"` // next page id
	PrevID interface{} `json:"prev_id" xml:"prev_id"` // prev page id
	Count  int64       `json:"count" xml:"count"`     // number of qualified data items according to all filter conditions
	Rows   int         `json:"rows" xml:"rows"`       // Display the number of entries per page
}

Result Result Object

type Sort

type Sort int

Sort sort

const (
	// Desc desc
	Desc Sort = -1
	// Asc asc
	Asc = 1
)

type SortInfo

type SortInfo struct {
	Key  string
	Sort Sort
}

SortInfo sort info

func ParseSorts

func ParseSorts(request *http.Request, filterMapping map[string]string) []SortInfo

ParseSorts Parse the sort field, and the passed-in rule is sorts=-filed1,+field2,field3

"-"  The "-" sign identifies the descending order.
"+" the "+" or unsigned ascending order

type Where

type Where map[string]interface{}

Where filter

Directories

Path Synopsis

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL