Skip to content

Instantly share code, notes, and snippets.

@inlinestyle
Created September 5, 2014 03:56
Show Gist options
  • Select an option

  • Save inlinestyle/3c499be2457b4e85cec3 to your computer and use it in GitHub Desktop.

Select an option

Save inlinestyle/3c499be2457b4e85cec3 to your computer and use it in GitHub Desktop.
Boilerplate for a stream API in go
package main
import (
"fmt"
"github.com/codegangsta/martini-contrib/binding"
"github.com/go-martini/martini"
"gopkg.in/mgo.v2"
"gopkg.in/mgo.v2/bson"
"net/http"
)
// Using this over mgo.DBRef because it wouldn't coerce JSON correctly
type EventRef struct {
Id bson.ObjectId `bson:"$id" json:"$id"`
Type string `bson:"$ref" json:"$ref"`
}
type Stream struct {
Id bson.ObjectId `bson:"_id"`
Type string `bson:"_type" json:"_type"`
Events []EventRef
DeviceId string `bson:"device_id" json:"device_id"`
}
func main() {
session, err := mgo.Dial("localhost:27017")
if err != nil {
panic(err)
}
defer session.Close()
m := martini.Classic()
m.Map(session)
m.Post("/stream/(?P<id>\\w{24})", binding.Json(Stream{}), func(newStream Stream, params martini.Params, session *mgo.Session) {
streamId := bson.ObjectIdHex(params["id"])
var oldStream Stream
streams := session.DB("streams").C("stream")
err := streams.Find(bson.M{"_id": streamId}).One(&oldStream)
if err == nil {
fmt.Println("Handling pre-existing stream")
// These should look identical if your POST JSON matches the saved record
fmt.Println(newStream)
fmt.Println(oldStream)
} else if err == mgo.ErrNotFound {
fmt.Println("Handling brand new stream")
} else {
panic(err)
}
})
http.ListenAndServe(":8011", m)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment