Created
June 22, 2014 17:46
-
-
Save brly/37c44f51a7908730c161 to your computer and use it in GitHub Desktop.
martini json response sample
This file contains 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/go-martini/martini" | |
"github.com/martini-contrib/render" | |
"labix.org/v2/mgo" | |
"labix.org/v2/mgo/bson" | |
"net/http" | |
) | |
type User struct { | |
Name string `json:"name"` | |
Value int `json:"value"` | |
} | |
func Mongo() martini.Handler { | |
session, err := mgo.Dial("localhost") | |
if err != nil { | |
panic(err) | |
} | |
return func(c martini.Context) { | |
reqSession := session.Clone() | |
c.Map(reqSession.DB("test")) | |
defer reqSession.Close() | |
c.Next() | |
} | |
} | |
func main() { | |
m := martini.Classic() | |
m.Use(martini.Static("public/angular/app")) | |
m.Use(Mongo()) | |
m.Use(render.Renderer(render.Options{ | |
Charset: "UTF-8", | |
})) | |
m.Get("/samplejson", func(r render.Render) { | |
json := map[string]interface{}{"hoge": 100, "key": [3]int{1, 2, 3}} | |
r.JSON(200, json) | |
}) | |
m.Get("/user", func(r render.Render) { | |
r.JSON(200, User{Name: "Yunocchi", Value: 100}) | |
}) | |
m.Get("/users", func(r render.Render) { | |
array := []User{{Name: "a", Value: 1}, {Name: "b", Value: 2}} | |
r.JSON(200, array) | |
}) | |
m.Get("/mongodb", func(params martini.Params, writer http.ResponseWriter, db *mgo.Database, r render.Render) { | |
writer.Header().Set("Content-Type", "application/json") | |
var result []struct { | |
Name string | |
Value int | |
} | |
db.C("test").Find(bson.M{}).All(&result) | |
r.JSON(200, result) | |
// if result != nil { | |
// r.JSON(200, result) | |
// } | |
// r.JSON(200, map[string]interface{}{"a": 1}) | |
}) | |
m.Run() | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment