This is an except of code I have which uses goji and the mgo driver, I want to change this to use the official driver for golang:
func main() {
session, err := mgo.Dial("mongo")
if err != nil {
panic(err)
}
defer session.Close()
session.SetMode(mgo.Monotonic, true)
ensureIndex(session)
mux := goji.NewMux()
mux.HandleFunc(pat.Get("/cars"), allCars(session))
mux.HandleFunc(pat.Post("/cars"), addCar(session))
mux.HandleFunc(pat.Get("/cars/:vin"), carByVIN(session))
mux.HandleFunc(pat.Delete("/cars/:vin"), deleteCar(session))
http.ListenAndServe(":8080", mux)
}
func allCars(s *mgo.Session) func(w http.ResponseWriter, r *http.Request) {
return func(w http.ResponseWriter, r *http.Request) {
session := s.Copy()
defer session.Close()
c := session.DB("carsupermarket").C("cars")
var cars []vehicle
err := c.Find(bson.M{}).All(&cars)
if err != nil {
errorWithJSON(w, "Database error", http.StatusInternalServerError)
log.Println("Failed get all cars: ", err)
return
}
respBody, err := json.MarshalIndent(cars, "", " ")
if err != nil {
log.Fatal(err)
}
responseWithJSON(w, respBody, http.StatusOK)
}
}
In terms of passing connectivity / session information to my goji handler functions what would people recommend ?, a pointer to a collection ?