Skip to content

Instantly share code, notes, and snippets.

@kabala

kabala/rest-mongo.go

Forked from narate/rest-mongo.go
Last active Apr 24, 2016
Embed
What would you like to do?
Golang RESTful with MongoDB
// modified by Carlos Santín
// Based on gist rest-mongo.go by : Narate Ketram
// twitter @kabalism
package main
import (
"github.com/ant0ine/go-json-rest/rest"
"gopkg.in/mgo.v2"
"gopkg.in/mgo.v2/bson"
"log"
"net/http"
)
type Person struct {
UserName string `json:"username" bson:"username"`
Name string `json:"name" bson:"name"`
LastName string `json:"lastname" bson:"lastname"`
Email string `json:"email" bson:"email"`
Profession string `json:"profession" bson:"profession"`
}
type Err struct {
ErrCode int
ErrMsg string
}
func FindUser(user string) (Person, error) {
session, err := mgo.Dial("127.0.0.1")
p := Person{}
if err != nil {
return p, err
}
defer session.Close()
c := session.DB("app_db").C("users")
if err = c.Find(bson.M{"username": user}).One(&p); err != nil {
return p, err
}
return p, nil
}
func AddUser(p Person) (err_msg Err) {
session, err := mgo.Dial("127.0.0.1")
if err != nil {
err_msg = Err{1, "connection failed"}
}
defer session.Close()
c := session.DB("app_db").C("users")
tp := Person{} // temp person :P
// if not found add new user
// else return error user already exist
if err := c.Find(bson.M{"username": &p.UserName}).One(&tp); err != nil {
err_msg = Err{0, "done"}
if err := c.Insert(&p); err != nil {
err_msg = Err{1, "insert failed"}
}
} else {
err_msg = Err{1, "user already exist"}
}
return
}
func GetUser(w rest.ResponseWriter, req *rest.Request) {
name, err := FindUser(req.PathParam("name"))
if err != nil {
err_msg := Err{1, "Not found"}
w.WriteJson(&err_msg)
} else {
w.WriteJson(&name)
}
}
func NewUser(w rest.ResponseWriter, req *rest.Request) {
p := Person{}
err_msg := Err{}
if err := req.DecodeJsonPayload(&p); err != nil {
rest.Error(w, err.Error(), http.StatusInternalServerError)
return
} else {
err_msg = AddUser(p)
}
w.WriteJson(&err_msg)
}
func main() {
api := rest.NewApi()
api.Use(rest.DefaultDevStack...)
router, err := rest.MakeRouter(
//rest.Get("/users", GetAllUsers),
rest.Post("/new", NewUser),
rest.Get("/u/:name", GetUser),
//rest.Put("/users/:id", PutUser),
//rest.Delete("/users/:id", DeleteUser),
)
if err != nil {
log.Fatal(err)
}
api.SetApp(router)
log.Fatal(http.ListenAndServe(":8080", api.MakeHandler()))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment