Skip to content

Commit

Permalink
adding pagination
Browse files Browse the repository at this point in the history
  • Loading branch information
ali-assar committed Mar 12, 2024
1 parent 31d7cf6 commit 99cb231
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 3 deletions.
17 changes: 16 additions & 1 deletion app/app.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ package app
import (
"bytes"
"net/http"
"strconv"
"time"

"github.com/gin-gonic/gin"
Expand All @@ -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
}
Expand Down Expand Up @@ -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
}
Expand Down
5 changes: 3 additions & 2 deletions database/database.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
}
Expand Down

0 comments on commit 99cb231

Please sign in to comment.