Skip to content

Commit

Permalink
09-Pagination add paginate
Browse files Browse the repository at this point in the history
  • Loading branch information
bonfy committed Oct 8, 2018
1 parent f106252 commit fd3c825
Show file tree
Hide file tree
Showing 10 changed files with 106 additions and 10 deletions.
2 changes: 2 additions & 0 deletions controller/g.go
Original file line number Original file line Diff line number Diff line change
Expand Up @@ -12,13 +12,15 @@ var (
sessionName string sessionName string
flashName string flashName string
store *sessions.CookieStore store *sessions.CookieStore
pageLimit int
) )


func init() { func init() {
templates = PopulateTemplates() templates = PopulateTemplates()
store = sessions.NewCookieStore([]byte("something-very-secret")) store = sessions.NewCookieStore([]byte("something-very-secret"))
sessionName = "go-mega" sessionName = "go-mega"
flashName = "go-flash" flashName = "go-flash"
pageLimit = 5
} }


// Startup func // Startup func
Expand Down
6 changes: 4 additions & 2 deletions controller/home.go
Original file line number Original file line Diff line number Diff line change
Expand Up @@ -28,10 +28,11 @@ func (h home) registerRoutes() {
func indexHandler(w http.ResponseWriter, r *http.Request) { func indexHandler(w http.ResponseWriter, r *http.Request) {
tpName := "index.html" tpName := "index.html"
vop := vm.IndexViewModelOp{} vop := vm.IndexViewModelOp{}
page := getPage(r)
username, _ := getSessionUser(r) username, _ := getSessionUser(r)
if r.Method == http.MethodGet { if r.Method == http.MethodGet {
flash := getFlash(w, r) flash := getFlash(w, r)
v := vop.GetVM(username, flash) v := vop.GetVM(username, flash, page, pageLimit)
templates[tpName].Execute(w, &v) templates[tpName].Execute(w, &v)
} }
if r.Method == http.MethodPost { if r.Method == http.MethodPost {
Expand Down Expand Up @@ -119,8 +120,9 @@ func profileHandler(w http.ResponseWriter, r *http.Request) {
vars := mux.Vars(r) vars := mux.Vars(r)
pUser := vars["username"] pUser := vars["username"]
sUser, _ := getSessionUser(r) sUser, _ := getSessionUser(r)
page := getPage(r)
vop := vm.ProfileViewModelOp{} vop := vm.ProfileViewModelOp{}
v, err := vop.GetVM(sUser, pUser) v, err := vop.GetVM(sUser, pUser, page, pageLimit)
if err != nil { if err != nil {
msg := fmt.Sprintf("user ( %s ) does not exist", pUser) msg := fmt.Sprintf("user ( %s ) does not exist", pUser)
w.Write([]byte(msg)) w.Write([]byte(msg))
Expand Down
17 changes: 17 additions & 0 deletions controller/utils.go
Original file line number Original file line Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import (
"net/http" "net/http"
"os" "os"
"regexp" "regexp"
"strconv"


"github.com/bonfy/go-mega-code/vm" "github.com/bonfy/go-mega-code/vm"
) )
Expand Down Expand Up @@ -192,3 +193,19 @@ func getFlash(w http.ResponseWriter, r *http.Request) string {
session.Save(r, w) session.Save(r, w)
return fmt.Sprintf("%v", fm[0]) return fmt.Sprintf("%v", fm[0])
} }

func getPage(r *http.Request) int {
url := r.URL // net/url.URL
query := url.Query() // Values (map[string][]string)

q := query.Get("page")
if q == "" {
return 1
}

page, err := strconv.Atoi(q)
if err != nil {
return 1
}
return page
}
12 changes: 12 additions & 0 deletions model/post.go
Original file line number Original file line Diff line number Diff line change
Expand Up @@ -21,3 +21,15 @@ func GetPostsByUserID(id int) (*[]Post, error) {
} }
return &posts, nil return &posts, nil
} }

// GetPostsByUserIDPageAndLimit func
func GetPostsByUserIDPageAndLimit(id, page, limit int) (*[]Post, int, error) {
var total int
var posts []Post
offset := (page - 1) * limit
if err := db.Preload("User").Order("timestamp desc").Where("user_id=?", id).Offset(offset).Limit(limit).Find(&posts).Error; err != nil {
return nil, total, err
}
db.Model(&Post{}).Where("user_id=?", id).Count(&total)
return &posts, total, nil
}
13 changes: 13 additions & 0 deletions model/user.go
Original file line number Original file line Diff line number Diff line change
Expand Up @@ -96,6 +96,19 @@ func (u *User) FollowingPosts() (*[]Post, error) {
return &posts, nil return &posts, nil
} }


// FollowingPostsByPageAndLimit func
func (u *User) FollowingPostsByPageAndLimit(page, limit int) (*[]Post, int, error) {
var total int
var posts []Post
offset := (page - 1) * limit
ids := u.FollowingIDs()
if err := db.Preload("User").Order("timestamp desc").Where("user_id in (?)", ids).Offset(offset).Limit(limit).Find(&posts).Error; err != nil {
return nil, total, err
}
db.Model(&Post{}).Where("user_id in (?)", ids).Count(&total)
return &posts, total, nil
}

// IsFollowedByUser func // IsFollowedByUser func
func (u *User) IsFollowedByUser(username string) bool { func (u *User) IsFollowedByUser(username string) bool {
user, _ := GetUserByUsername(username) user, _ := GetUserByUsername(username)
Expand Down
10 changes: 9 additions & 1 deletion templates/content/index.html
Original file line number Original file line Diff line number Diff line change
Expand Up @@ -16,8 +16,16 @@ <h1>Hello, {{.CurrentUser}}!</h1>
<table> <table>
<tr valign="top"> <tr valign="top">
<td><img src="{{.User.Avatar}}&s=36"></td> <td><img src="{{.User.Avatar}}&s=36"></td>
<td>{{ .User.Username }} says:<br>{{ .Body }}</td> <td><a href="/user/{{.User.Username}}">{{ .User.Username }}</a> says:<br>{{ .Body }}</td>
</tr> </tr>
</table> </table>
{{end}} {{end}}

{{ if gt .PrevPage 0 }}
<a href="/?page={{.PrevPage}}">Newer posts</a>
{{ end }}
{{ if gt .NextPage 0 }}
<a href="/?page={{.NextPage}}">Older posts</a>
{{ end }}

{{end}} {{end}}
9 changes: 8 additions & 1 deletion templates/content/profile.html
Original file line number Original file line Diff line number Diff line change
Expand Up @@ -34,9 +34,16 @@ <h1>User: {{.ProfileUser.Username}}</h1>
<table> <table>
<tr valign="top"> <tr valign="top">
<td><img src="{{.User.Avatar}}&s=36"></td> <td><img src="{{.User.Avatar}}&s=36"></td>
<td>{{ .User.Username }} says:<br>{{ .Body }}</td> <td><a href="/user/{{.User.Username}}">{{ .User.Username }}</a> says:<br>{{ .Body }}</td>
</tr> </tr>
</table> </table>
{{end}} {{end}}


{{ if gt .PrevPage 0 }}
<a href="/user/{{.ProfileUser.Username}}?page={{.PrevPage}}">Newer posts</a>
{{ end }}
{{ if gt .NextPage 0 }}
<a href="/user/{{.ProfileUser.Username}}?page={{.NextPage}}">Older posts</a>
{{ end }}

{{end}} {{end}}
28 changes: 28 additions & 0 deletions vm/g.go
Original file line number Original file line Diff line number Diff line change
Expand Up @@ -15,3 +15,31 @@ func (v *BaseViewModel) SetTitle(title string) {
func (v *BaseViewModel) SetCurrentUser(username string) { func (v *BaseViewModel) SetCurrentUser(username string) {
v.CurrentUser = username v.CurrentUser = username
} }

// BasePageViewModel struct
type BasePageViewModel struct {
PrevPage int
NextPage int
Total int
CurrentPage int
Limit int
}

// SetPrevAndNextPage func
func (v *BasePageViewModel) SetPrevAndNextPage() {
if v.CurrentPage > 1 {
v.PrevPage = v.CurrentPage - 1
}

if (v.Total-1)/v.Limit >= v.CurrentPage {
v.NextPage = v.CurrentPage + 1
}
}

// SetBasePageViewModel func
func (v *BasePageViewModel) SetBasePageViewModel(total, page, limit int) {
v.Total = total
v.CurrentPage = page
v.Limit = limit
v.SetPrevAndNextPage()
}
12 changes: 9 additions & 3 deletions vm/index.go
Original file line number Original file line Diff line number Diff line change
Expand Up @@ -7,16 +7,22 @@ type IndexViewModel struct {
BaseViewModel BaseViewModel
Posts []model.Post Posts []model.Post
Flash string Flash string

BasePageViewModel
} }


// IndexViewModelOp struct // IndexViewModelOp struct
type IndexViewModelOp struct{} type IndexViewModelOp struct{}


// GetVM func // GetVM func
func (IndexViewModelOp) GetVM(username string, flash string) IndexViewModel { func (IndexViewModelOp) GetVM(username, flash string, page, limit int) IndexViewModel {
u, _ := model.GetUserByUsername(username) u, _ := model.GetUserByUsername(username)
posts, _ := u.FollowingPosts() posts, total, _ := u.FollowingPostsByPageAndLimit(page, limit)
v := IndexViewModel{BaseViewModel{Title: "Homepage"}, *posts, flash} v := IndexViewModel{}
v.SetTitle("Homepage")
v.Posts = *posts
v.Flash = flash
v.SetBasePageViewModel(total, page, limit)
v.SetCurrentUser(username) v.SetCurrentUser(username)
return v return v
} }
Expand Down
7 changes: 4 additions & 3 deletions vm/profile.go
Original file line number Original file line Diff line number Diff line change
Expand Up @@ -11,23 +11,24 @@ type ProfileViewModel struct {
FollowersCount int FollowersCount int
FollowingCount int FollowingCount int
ProfileUser model.User ProfileUser model.User
BasePageViewModel
} }


// ProfileViewModelOp struct // ProfileViewModelOp struct
type ProfileViewModelOp struct{} type ProfileViewModelOp struct{}


// GetVM func // GetVM func
func (ProfileViewModelOp) GetVM(sUser, pUser string) (ProfileViewModel, error) { func (ProfileViewModelOp) GetVM(sUser, pUser string, page, limit int) (ProfileViewModel, error) {
v := ProfileViewModel{} v := ProfileViewModel{}
v.SetTitle("Profile") v.SetTitle("Profile")
u, err := model.GetUserByUsername(pUser) u, err := model.GetUserByUsername(pUser)
if err != nil { if err != nil {
return v, err return v, err
} }
posts, _ := model.GetPostsByUserID(u.ID) posts, total, _ := model.GetPostsByUserIDPageAndLimit(u.ID, page, limit)
v.ProfileUser = *u v.ProfileUser = *u
v.Editable = (sUser == pUser) v.Editable = (sUser == pUser)

v.SetBasePageViewModel(total, page, limit)
if !v.Editable { if !v.Editable {
v.IsFollow = u.IsFollowedByUser(sUser) v.IsFollow = u.IsFollowedByUser(sUser)
} }
Expand Down

0 comments on commit fd3c825

Please sign in to comment.