Last active
August 29, 2015 13:55
-
-
Save techslides/8770446 to your computer and use it in GitHub Desktop.
Martini and Binding utility for reading form params and validation
This file contains hidden or 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
| //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) | |
| } | |
| } |
Author
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/simple-app-with-go-martini-gorp-and-mysql/