Last active
August 29, 2015 13:56
-
-
Save techslides/8945100 to your computer and use it in GitHub Desktop.
Martini Routes for PUT and DELETE calls to users
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//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) | |
} | |
}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Learn more about this code here: http://techslides.com/martini-app-with-ajax-json-and-user-sessions/