Last active
August 29, 2015 13:55
-
-
Save techslides/8758589 to your computer and use it in GitHub Desktop.
SQL INSERT with Go Lang and Martini
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
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() | |
} |
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/