Skip to content

Instantly share code, notes, and snippets.

@nise-nabe
Last active December 15, 2015 08:49
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nise-nabe/5234154 to your computer and use it in GitHub Desktop.
Save nise-nabe/5234154 to your computer and use it in GitHub Desktop.
mymysql を使った revel の mysql プラグイン
import (
"database/sql"
"github.com/robfig/revel"
_ "github.com/ziutek/mymysql/godrv"
)
var (
db *sql.DB
)
type MySQLPlugin struct {
revel.EmptyPlugin
}
func (p MySQLPlugin) OnAppStart() {
host, _ := revel.Config.String("db.host")
port, _ := revel.Config.String("db.port")
dbname, _ := revel.Config.String("db.name")
user, _ := revel.Config.String("db.user")
pass, _ := revel.Config.String("db.pass")
var err error
db, err = sql.Open("mymysql", "tcp:"+host+":"+port+"*"+dbname+"/"+user+"/"+pass)
if err != nil {
panic(err)
}
}
func (p MySQLPlugin) BeforeRequest(c *revel.Controller) {
txn, err := db.Begin()
if err != nil {
panic(err)
}
c.Txn = txn
}
func (p MySQLPlugin) AfterRequest(c *revel.Controller) {
c.Txn.Commit()
c.Txn = nil
}
func (p MySQLPlugin) OnException(c *revel.Controller, err interface{}) {
if c.Txn != nil {
c.Txn.Rollback()
}
}
func init() {
revel.RegisterPlugin(MySQLPlugin{})
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment