Skip to content

Instantly share code, notes, and snippets.

@techslides
Last active August 29, 2015 13:55
Show Gist options
  • Select an option

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

Select an option

Save techslides/8770446 to your computer and use it in GitHub Desktop.
Martini and Binding utility for reading form params and validation
//needs import ("github.com/codegangsta/martini-contrib/binding")
type Post struct {
Id int64 `db:"post_id"`
Created int64
Title string `form:"Title"`
Body string `form:"Body" binding:"required"`
}
func (bp Post) Validate(errors *binding.Errors, req *http.Request) {
if len(bp.Title) == 0 {
errors.Fields["title"] = "Title cannot be empty"
}
}
//make a post
m.Post("/", binding.Bind(Post{}), func(post Post, r render.Render) {
p1 := newPost(post.Title, post.Body)
err = dbmap.Insert(&p1)
checkErr(err, "Insert failed")
newmap := map[string]interface{}{"metatitle": "created post", "post": p1}
r.HTML(200, "post", newmap)
})
func checkErr(err error, msg string) {
if err != nil {
log.Fatalln(msg, err)
}
}
@techslides
Copy link
Copy Markdown
Author

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