10 items per page on search

This commit is contained in:
Las Zenow 2012-07-30 23:59:55 +02:00
parent c64226ffb9
commit b70ddd81ab
2 changed files with 40 additions and 1 deletions

View file

@ -1,12 +1,17 @@
package main
import (
"strconv"
"labix.org/v2/mgo"
"labix.org/v2/mgo/bson"
"net/http"
"strings"
)
const (
ITEMS_PAGE = 10
)
func buildQuery(q string) bson.M {
words := strings.Split(q, " ")
reg := make([]bson.RegEx, len(words))
@ -19,7 +24,11 @@ func buildQuery(q string) bson.M {
type searchData struct {
Search string
Found int
Books []Book
Page int
Next string
Prev string
}
func searchHandler(coll *mgo.Collection, w http.ResponseWriter, r *http.Request) {
@ -31,5 +40,29 @@ func searchHandler(coll *mgo.Collection, w http.ResponseWriter, r *http.Request)
req := strings.Join(r.Form["q"], " ")
var res []Book
coll.Find(buildQuery(req)).All(&res)
loadTemplate(w, "search", searchData{req, res})
page := 0
if len(r.Form["p"]) != 0 {
page, err = strconv.Atoi(r.Form["p"][0])
if err != nil || len(res) < ITEMS_PAGE*page {
page = 0
}
}
var data searchData
data.Search = req
data.Found = len(res)
if len(res) > ITEMS_PAGE*(page+1) {
data.Books = res[ITEMS_PAGE*page:ITEMS_PAGE*(page+1)]
} else {
data.Books = res[ITEMS_PAGE*page:]
}
data.Page = page+1
if len(res) > (page+1)*ITEMS_PAGE {
data.Next = "/search/?q=" + req + "&p=" + strconv.Itoa(page+1)
}
if page > 0 {
data.Prev = "/search/?q=" + req + "&p=" + strconv.Itoa(page-1)
}
loadTemplate(w, "search", data)
}

View file

@ -4,6 +4,8 @@
<input type="submit" value="Search">
</form>
<p>Found {{.Found}} books. Page {{.Page}}</p>
<ul>
{{with .Books}}
{{range .}}
@ -11,3 +13,7 @@
{{end}}
{{end}}
</ul>
<p>
{{if .Prev}}<a href="{{.Prev}}">&lt;Prev</a> {{end}}
{{if .Next}}<a href="{{.Next}}">Next&gt;</a>{{end}}</p>