From 99cb231be60773b8e765ae4a778143a9a0c27f9e Mon Sep 17 00:00:00 2001 From: ali Date: Tue, 12 Mar 2024 10:39:03 +0330 Subject: [PATCH] adding pagination --- app/app.go | 17 ++++++++++++++++- database/database.go | 5 +++-- 2 files changed, 19 insertions(+), 3 deletions(-) diff --git a/app/app.go b/app/app.go index 1cf8664..0e9ac5c 100644 --- a/app/app.go +++ b/app/app.go @@ -3,6 +3,7 @@ package app import ( "bytes" "net/http" + "strconv" "time" "github.com/gin-gonic/gin" @@ -29,6 +30,11 @@ func SetupRoutes(app_settings common.AppSettings, database database.Database) *g // DO not cache as it needs to handlenew form values r.POST("/contact-send", makeContactFormHandler()) + // this will setup the route for pagination + r.GET("/page/:num", func(c *gin.Context) { + homeHandler(c, app_settings, database) + }) + r.Static("/static", "./static") return r } @@ -75,7 +81,16 @@ func addCachableHandler(e *gin.Engine, method string, endpoint string, generator // / This function will act as the handler for // / the home page func homeHandler(c *gin.Context, settings common.AppSettings, db database.Database) ([]byte, error) { - posts, err := db.GetPosts() + pageNumQuery := c.Param("num") + pageNum, err := strconv.Atoi(pageNumQuery) + if err != nil { + return nil, err + } + + limit := 10 // or whatever limit you want + offset := (pageNum - 1) * limit + + posts, err := db.GetPosts(limit, offset) if err != nil { return nil, err } diff --git a/database/database.go b/database/database.go index 79b8ed2..132d6e4 100644 --- a/database/database.go +++ b/database/database.go @@ -28,8 +28,9 @@ type SqlDatabase struct { // / This function gets all the posts from the current // / database connection. -func (db SqlDatabase) GetPosts() (all_posts []common.Post, err error) { - rows, err := db.Connection.Query("SELECT title, excerpt, id FROM posts;") +func (db SqlDatabase) GetPosts(limit int, offset int) (all_posts []common.Post, err error) { + query := fmt.Sprintf("SELECT title, excerpt, id FROM posts LIMIT %d OFFSET %d;", limit, offset) + rows, err := db.Connection.Query(query) if err != nil { return make([]common.Post, 0), err }