Last active
December 30, 2015 17:28
-
-
Save codegangsta/7860922 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"github.com/codegangsta/martini" | |
"github.com/codegangsta/martini-contrib/binding" | |
"github.com/codegangsta/martini-contrib/render" | |
"labix.org/v2/mgo" | |
) | |
type Wish struct { | |
Name string `form:"name"` | |
Description string `form:"description"` | |
} | |
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("advent")) | |
} | |
} | |
func GetAll(db *mgo.Database) []Wish { | |
var wishlist []Wish | |
db.C("wishes").Find(nil).All(&wishlist) | |
return wishlist | |
} | |
func main() { | |
m := martini.Classic() | |
m.Use(render.Renderer()) | |
m.Use(DB()) | |
m.Get("/wishes", func(r render.Render, db *mgo.Database) { | |
r.HTML(200, "list", GetAll(db)) | |
}) | |
m.Post("/wishes", binding.Form(Wish{}), func(r render.Render, db *mgo.Database, wish Wish) { | |
db.C("wishes").Insert(wish) | |
r.HTML(200, "list", GetAll(db)) | |
}) | |
m.Run() | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment