Skip to content

Instantly share code, notes, and snippets.

@techslides
Last active August 29, 2015 13:55
Show Gist options
  • Save techslides/8758589 to your computer and use it in GitHub Desktop.
Save techslides/8758589 to your computer and use it in GitHub Desktop.
SQL INSERT with Go Lang and Martini
package main
import (
"database/sql"
"github.com/codegangsta/martini"
"github.com/codegangsta/martini-contrib/render"
"github.com/codegangsta/martini-contrib/binding"
_ "github.com/go-sql-driver/mysql"
"html/template"
)
type Blog struct {
Id int `form:"Id"`
Title string `form:"Title"`
Date string `form:"Date"`
Description template.HTML `form:"Description"`
Author int `form:"Author"`
}
func main() {
m := martini.Classic()
//render html templates from directory
m.Use(render.Renderer(render.Options{Directory: "templates"}))
db, err := sql.Open("mysql", "USERNAME:PASSSWORD@unix(/var/run/mysqld/mysqld.sock)/martini_blog");
if err != nil {
panic(err.Error()) // Just for example purpose. You should use proper error handling instead of panic
}
defer db.Close()
m.Post("/make", binding.Bind(Blog{}), func(blog Blog) string {
//should it be even stored as template.HTML
desc := string(blog.Description)
stmt, es := db.Prepare("insert into blogs values(?,?,?,?,?)")
if es != nil {
panic(es.Error())
}
_, er := stmt.Exec(blog.Id,blog.Title,blog.Date,desc,blog.Author)
if er != nil {
panic(er.Error())
}
return blog.Title
})
m.Run()
}
@techslides
Copy link
Author

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