Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Golang RESTful with MongoDB
// created by : Narate Ketram
package main
import (
"fmt"
"github.com/ant0ine/go-json-rest"
"labix.org/v2/mgo"
"labix.org/v2/mgo/bson"
"net/http"
)
type Person struct {
UserName string
FullName string
Phone string
Age int
Gender string
}
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("godb").C("people")
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("godb").C("people")
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() {
handler := rest.ResourceHandler{}
handler.SetRoutes(
rest.Route{"Get","/u/:name", GetUser},
rest.Route{"Post","/new", NewUser},
)
fmt.Println("Run on 127.0.0.1:8090")
http.ListenAndServe(":8090", &handler)
}
@kabala

This comment has been minimized.

Copy link

@kabala kabala commented Apr 19, 2016

thank you!!

@dezza

This comment has been minimized.

Copy link

@dezza dezza commented Dec 13, 2017

if err := c.Find(bson.M{"username":&p.UserName}).One(&tp);err != nil {

I wonder if there are other ways to query for existance of an object. I tried using .Count() and it returns "n, err" 0, nil on everything I throw at it.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment