Skip to content

Instantly share code, notes, and snippets.

@techslides
Created February 11, 2014 22:23
Show Gist options
  • Select an option

  • Save techslides/8945495 to your computer and use it in GitHub Desktop.

Select an option

Save techslides/8945495 to your computer and use it in GitHub Desktop.
Updating a post with authentication and user validation
//Update a post
m.Put("/posts/:id", binding.Bind(Post{}), func(args martini.Params, post Post, r render.Render, authuser sessionauth.User) {
//capture passed in parameters from Ajax call
var newTitle = post.Title
var newBody = post.Body
//retrieve the post to retrieve original owner
err = dbmap.SelectOne(&post, "select * from posts where post_id=?", args["id"])
//simple DB error check
if err != nil {
newmap := map[string]interface{}{"message":"Something went wrong."}
r.JSON(400, newmap)
} else {
//owner check
if(authuser.UniqueId() == post.UserId){
//assign new values to the retrieved post
post.Title=newTitle
post.Body=newBody
//update the post
count, err := dbmap.Update(&post)
checkErr(err, "Update failed")
if count == 1 {
newmap := map[string]interface{}{"responseText":"success"}
r.JSON(200, newmap)
} else {
newmap := map[string]interface{}{"responseText":"error"}
r.JSON(400, newmap)
}
} else {
newmap := map[string]interface{}{"responseText":"You are not allowed to modify this resource."}
r.JSON(403, newmap)
}
}
})
@techslides
Copy link
Copy Markdown
Author

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