This repository has been archived on 2025-03-01. You can view files and clone it, but cannot push or open issues or pull requests.
trantor/search.go

71 lines
1.4 KiB
Go
Raw Normal View History

2012-07-30 23:23:38 +02:00
package main
import (
2012-07-30 23:59:55 +02:00
"strconv"
2012-07-30 23:23:38 +02:00
"labix.org/v2/mgo"
"labix.org/v2/mgo/bson"
"net/http"
"strings"
)
2012-07-30 23:59:55 +02:00
const (
ITEMS_PAGE = 10
)
2012-07-30 23:23:38 +02:00
func buildQuery(q string) bson.M {
words := strings.Split(q, " ")
reg := make([]bson.RegEx, len(words))
for i, w := range words {
reg[i].Pattern = w
reg[i].Options = "i"
}
return bson.M{"keywords": bson.M{"$all": reg}}
}
type searchData struct {
Search string
2012-07-30 23:59:55 +02:00
Found int
2012-07-30 23:23:38 +02:00
Books []Book
2012-07-30 23:59:55 +02:00
Page int
Next string
Prev string
2012-07-30 23:23:38 +02:00
}
2012-08-15 13:58:16 +02:00
func searchHandler(coll *mgo.Collection) func(http.ResponseWriter, *http.Request) {
return func(w http.ResponseWriter, r *http.Request) {
err := r.ParseForm()
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
req := strings.Join(r.Form["q"], " ")
var res []Book
coll.Find(buildQuery(req)).All(&res)
2012-07-30 23:59:55 +02:00
2012-08-15 13:58:16 +02:00
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
}
2012-07-30 23:59:55 +02:00
}
2012-08-15 13:58:16 +02:00
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)
2012-07-30 23:59:55 +02:00
}
2012-07-30 23:23:38 +02:00
}