/
server.go
57 lines (45 loc) · 1.13 KB
/
server.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
package main
import (
"github.com/go-martini/martini"
"github.com/martini-contrib/binding"
"github.com/martini-contrib/render"
"github.com/martini-contrib/gzip"
"labix.org/v2/mgo"
)
type Quote struct {
Content string `form:"content"`
}
func DB() martini.Handler {
session, err := mgo.Dial("mongodb://localhost")
if err != nil {
panic(err)
}
return func(c martini.Context) {
s := session.Clone()
c.Map(s.DB("quotes"))
}
}
func GetAll(db *mgo.Database) []Quote {
var quotes []Quote
db.C("quotes").Find(nil).All("es)
return quotes
}
func main() {
m := martini.Classic()
m.Use(gzip.All())
// render html templates from templates directory
m.Use(render.Renderer(render.Options{
Layout: "layout",
}))
m.Use(DB())
m.Get("/", func(r render.Render, db *mgo.Database) {
data := map[string]interface{}{"quotes": GetAll(db)}
r.HTML(200, "list", data)
})
m.Post("/", binding.Form(Quote{}), func(r render.Render, db *mgo.Database, quote Quote) {
db.C("quotes").Insert(quote)
data := map[string]interface{}{"quotes": GetAll(db)}
r.HTML(200, "list", data)
})
m.Run()
}