Skip to content

Instantly share code, notes, and snippets.

@techslides
Last active August 29, 2015 13:56
Show Gist options
  • Save techslides/8945100 to your computer and use it in GitHub Desktop.
Save techslides/8945100 to your computer and use it in GitHub Desktop.
Martini Routes for PUT and DELETE calls to users
//Update a user
m.Put("/users/:id", binding.Bind(User{}), func(args martini.Params, user User, r render.Render) {
//convert id from string to int64
f, _ := strconv.ParseInt(args["id"],0,64)
user.Id = f
count, err := dbmap.Update(&user)
checkErr(err, "Update failed")
//checkErr above logs the DB issue but we also need to present the proper response to the client
if count == 1 {
newmap := map[string]interface{}{"responseText":"success"}
r.JSON(200, newmap)
} else {
newmap := map[string]interface{}{"responseText":"error"}
r.JSON(400, newmap)
}
})
//Delete a User
m.Delete("/users/:id", func(args martini.Params, r render.Render) {
//convert id from string to int64
f, _ := strconv.ParseInt(args["id"],0,64)
//delete the user from the database
_, err = dbmap.Exec("delete from users where id=?", args["id"])
checkErr(err, "Delete failed")
//response with success or failure based on DB call
if err == nil {
newmap := map[string]interface{}{"responseText":"success"}
r.JSON(200, newmap)
//if you delete yourself, Ajax should redirect you
} else {
newmap := map[string]interface{}{"responseText":"error"}
r.JSON(400, newmap)
}
})
@techslides
Copy link
Author

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