-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpaginator.go
73 lines (55 loc) · 1.17 KB
/
paginator.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
package malak
import (
"net/http"
"strconv"
"github.com/ayinke-llc/malak/internal/pkg/util"
"go.opentelemetry.io/otel/attribute"
)
const (
defaultNumOfItemPerPage = 8
)
type PaginatedResultMetadata struct {
Total int64
}
type Paginator struct {
PerPage int64
Page int64
}
func (p Paginator) OTELAttributes() []attribute.KeyValue {
return []attribute.KeyValue{
attribute.Int64("per_page", p.PerPage),
attribute.Int64("page", p.Page),
}
}
func (p Paginator) Offset() int64 {
if p.Page <= 0 {
return 0
}
return (p.Page - 1) * p.PerPage
}
func PaginatorFromRequest(r *http.Request) Paginator {
defaultPage := 1
p := Paginator{
Page: int64(defaultPage),
PerPage: defaultNumOfItemPerPage,
}
if !util.IsStringEmpty(r.URL.Query().Get("page")) {
currentPage := r.URL.Query().Get("page")
var err error
dd, err := strconv.Atoi(currentPage)
if err != nil || p.Page <= 0 {
return p
}
p.Page = int64(dd)
}
if !util.IsStringEmpty(r.URL.Query().Get("per_page")) {
perPage := r.URL.Query().Get("per_page")
var err error
dd, err := strconv.Atoi(perPage)
if err != nil || p.PerPage <= 0 {
return p
}
p.PerPage = int64(dd)
}
return p
}