Added pager.
This commit is contained in:
parent
63f43e568c
commit
1f258ea17e
2 changed files with 63 additions and 0 deletions
|
|
@ -5,10 +5,15 @@ import (
|
||||||
"net/http"
|
"net/http"
|
||||||
|
|
||||||
"goweb/msg"
|
"goweb/msg"
|
||||||
|
"goweb/pager"
|
||||||
|
|
||||||
"github.com/labstack/echo/v4"
|
"github.com/labstack/echo/v4"
|
||||||
)
|
)
|
||||||
|
|
||||||
|
const (
|
||||||
|
DefaultItemsPerPage = 20
|
||||||
|
)
|
||||||
|
|
||||||
type Page struct {
|
type Page struct {
|
||||||
AppName string
|
AppName string
|
||||||
Title string
|
Title string
|
||||||
|
|
@ -25,6 +30,7 @@ type Page struct {
|
||||||
Description string
|
Description string
|
||||||
Keywords []string
|
Keywords []string
|
||||||
}
|
}
|
||||||
|
Pager pager.Pager
|
||||||
}
|
}
|
||||||
|
|
||||||
func NewPage(c echo.Context) Page {
|
func NewPage(c echo.Context) Page {
|
||||||
|
|
@ -33,6 +39,7 @@ func NewPage(c echo.Context) Page {
|
||||||
Reverse: c.Echo().Reverse,
|
Reverse: c.Echo().Reverse,
|
||||||
Path: c.Request().URL.Path,
|
Path: c.Request().URL.Path,
|
||||||
StatusCode: http.StatusOK,
|
StatusCode: http.StatusOK,
|
||||||
|
Pager: pager.NewPager(c, DefaultItemsPerPage),
|
||||||
}
|
}
|
||||||
|
|
||||||
p.IsHome = p.Path == "/"
|
p.IsHome = p.Path == "/"
|
||||||
|
|
|
||||||
56
pager/pager.go
Normal file
56
pager/pager.go
Normal file
|
|
@ -0,0 +1,56 @@
|
||||||
|
package pager
|
||||||
|
|
||||||
|
import (
|
||||||
|
"math"
|
||||||
|
"strconv"
|
||||||
|
|
||||||
|
"github.com/labstack/echo/v4"
|
||||||
|
)
|
||||||
|
|
||||||
|
type Pager struct {
|
||||||
|
Items int
|
||||||
|
Page int
|
||||||
|
ItemsPerPage int
|
||||||
|
Pages int
|
||||||
|
}
|
||||||
|
|
||||||
|
func NewPager(c echo.Context, itemsPerPage int) Pager {
|
||||||
|
p := Pager{
|
||||||
|
ItemsPerPage: itemsPerPage,
|
||||||
|
Page: 1,
|
||||||
|
}
|
||||||
|
|
||||||
|
if page := c.QueryParam("page"); page != "" {
|
||||||
|
if pageInt, err := strconv.Atoi(page); err != nil {
|
||||||
|
if pageInt > 0 {
|
||||||
|
p.Page = pageInt
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return p
|
||||||
|
}
|
||||||
|
|
||||||
|
func (p *Pager) SetItems(items int) {
|
||||||
|
p.Items = items
|
||||||
|
p.Pages = int(math.Ceil(float64(items) / float64(p.ItemsPerPage)))
|
||||||
|
|
||||||
|
if p.Page > p.Pages {
|
||||||
|
p.Page = p.Pages
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (p *Pager) IsBeginning() bool {
|
||||||
|
return p.Page == 1
|
||||||
|
}
|
||||||
|
|
||||||
|
func (p *Pager) IsEnd() bool {
|
||||||
|
return p.Page >= p.Pages
|
||||||
|
}
|
||||||
|
|
||||||
|
func (p *Pager) GetOffset() int {
|
||||||
|
if p.Page == 0 {
|
||||||
|
p.Page = 1
|
||||||
|
}
|
||||||
|
return (p.Page - 1) * p.ItemsPerPage
|
||||||
|
}
|
||||||
Loading…
Add table
Add a link
Reference in a new issue