func main() { mongo.GetConnection() router := httprouter.New() defaultUserWebService := resources.DefaultUserWebService{} router.GET("/users/:email", defaultUserWebService.GetUser) router.GET("/users", defaultUserWebService.GetUsers) router.POST("/users", defaultUserWebService.NewUser) router.PUT("/users/:email", defaultUserWebService.NewUser) http.ListenAndServe(":80", router) }
func (DefaultUserWebService) NewUser(writer http.ResponseWriter, request *http.Request, params httprouter.Params) { user := assembleUserFromRequest(request) mongoConnection := mongo.GetConnection() collection := mongoConnection.Session().DB(MongoDbSchema).C(MongoDbUserTable) err := collection.Insert(user) if err != nil { log.Fatal("couldn't insert users into mongo! ", err) } log.Println("User created: ", user) writer.Header().Set("Content-Type", "application/json") writer.WriteHeader(204) }
func (DefaultUserWebService) GetUsers(writer http.ResponseWriter, request *http.Request, params httprouter.Params) { mongoConnection := mongo.GetConnection() collection := mongoConnection.Session().DB(MongoDbSchema).C(MongoDbUserTable) result := []entities.User{} err := collection.Find(bson.M{}).All(&result) if err != nil { log.Fatal("couldn't find user in mongo! ", err) } log.Println("Retrieving users ", result) json.NewEncoder(writer).Encode(result) writer.Header().Set("Content-Type", "application/json") writer.WriteHeader(200) }