Last books added on index.html

This commit is contained in:
Las Zenow 2012-08-15 14:26:10 +02:00
parent 3db6231762
commit 52812c706b
2 changed files with 28 additions and 4 deletions

View file

@ -1,11 +1,21 @@
{{template "header.html"}}
<h1>Imperial Library of Trantor</h1>
<p><img src="/img/library.jpg" alt="library" /></p>
<form action="/search/">
<input type="search" name="q" />
<input type="submit" value="Search">
</form>
<p>Search on {{.}} books.</p>
<p><img src="/img/library.jpg" alt="library" /></p>
<p>Search on {{.Count}} books.</p>
<p>Last books added:
<ul>
{{with .Books}}
{{range .}}
<li><img src="{{.CoverSmall}}" alt="{{.Title}}" /><a href="/book/{{.Title}}">{{.Title}}</a> - {{range .Author}}{{.}}, {{end}}</li>
{{end}}
{{end}}
</ul>
</p>
{{template "footer.html"}}

View file

@ -30,6 +30,21 @@ func fileHandler(path string) {
http.Handle(path, http.StripPrefix(path, h))
}
type indexData struct {
Books []Book
Count int
}
func indexHandler(coll *mgo.Collection) func(http.ResponseWriter, *http.Request) {
var data indexData
data.Count, _ = coll.Count()
coll.Find(bson.M{}).Sort("-_id").Limit(10).All(&data.Books)
return func(w http.ResponseWriter, r *http.Request) {
loadTemplate(w, "index", data)
}
}
func main() {
session, err := mgo.Dial(IP)
if err != nil {
@ -37,7 +52,6 @@ func main() {
}
defer session.Close()
coll := session.DB(DB_NAME).C(BOOKS_COLL)
num, _ := coll.Count()
http.HandleFunc("/book/", bookHandler(coll))
http.HandleFunc("/search/", searchHandler(coll))
@ -46,6 +60,6 @@ func main() {
fileHandler("/img/")
fileHandler("/cover/")
fileHandler("/books/")
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) { loadTemplate(w, "index", num) })
http.HandleFunc("/", indexHandler(coll))
http.ListenAndServe(":8080", nil)
}