-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpagination.go
104 lines (90 loc) · 1.75 KB
/
pagination.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
package pagination
import (
"fmt"
"math"
)
var (
// Default MaxPer value if Pagination's MaxPer is not set.
DefaultMaxPer = 100
// Default DefaultPer value if Pagination's DefaultPer is not set.
DefaultDefaultPer = 10
)
type (
Pagination struct {
// The page value.
Page int `query:"page"`
// The per value.
Per int `query:"per"`
// Maximum per value.
MaxPer int
// DefaultPer is used if the per value is empty.
DefaultPer int
}
PaginationResult struct {
CurrentPage *int
NextPage *int
PrevPage *int
TotalPages *int
TotalCount *int
LimitValue *int
From *int
To *int
}
)
func (p Pagination) Limit() int {
return p.GetPer()
}
func (p Pagination) Offset() int {
return (p.GetPage() - 1) * p.GetPer()
}
func (p Pagination) LimitOffset() string {
return fmt.Sprintf("LIMIT %d OFFSET %d", p.Limit(), p.Offset())
}
func (p Pagination) GetPage() int {
page := p.Page
if page < 1 {
page = 1
}
return page
}
func (p Pagination) GetPer() int {
per, maxPer, defaultPer := p.Per, p.MaxPer, p.DefaultPer
if maxPer < 1 {
maxPer = DefaultMaxPer
}
if defaultPer < 1 {
defaultPer = DefaultDefaultPer
}
if per < 1 {
per = defaultPer
} else if per > maxPer {
per = maxPer
}
return per
}
func (p Pagination) PaginationResult(count int) (r PaginationResult) {
per, page := p.GetPer(), p.GetPage()
r = PaginationResult{
TotalCount: &count,
LimitValue: &per,
CurrentPage: &page,
}
tp, np, pp := int(math.Ceil(float64(count)/float64(per))), page+1, page-1
r.TotalPages = &tp
if np <= tp {
r.NextPage = &np
}
if pp > 0 {
r.PrevPage = &pp
}
if count > 0 && page <= tp {
from := pp*per + 1
to := page * per
if to > count {
to = count
}
r.From = &from
r.To = &to
}
return
}