Last active
December 15, 2015 08:49
-
-
Save nise-nabe/5234154 to your computer and use it in GitHub Desktop.
mymysql を使った revel の mysql プラグイン
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
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