Skip to content

Instantly share code, notes, and snippets.

@polidog
Created August 8, 2016 17:08
Show Gist options
  • Save polidog/8410a757af15e83ca82e61d817b4ac88 to your computer and use it in GitHub Desktop.
Save polidog/8410a757af15e83ca82e61d817b4ac88 to your computer and use it in GitHub Desktop.
GORMのMySQL接続のサンプル
[Database]
driver = "mysql"
server = ""
user = "hoge"
password = "fuga"
database = "testgo"
charset = "utf8"
parseTime = "true"
package main
import (
"fmt"
"github.com/BurntSushi/toml"
"github.com/jinzhu/gorm"
_ "github.com/jinzhu/gorm/dialects/mysql"
)
var db *gorm.DB
type Account struct {
gorm.Model
id int
email string
}
type Config struct {
Database DbConfig
}
func (c Config) Db() (string, string) {
return c.Database.Driver, c.Database.DSN()
}
type DbConfig struct {
Driver string
Server string
User string
Password string
Database string
Charset string
ParseTime string
}
func (d DbConfig) DSN() string {
return fmt.Sprintf("%s:%s@%s/%s?charset=%s&parseTime=%s", d.User, d.Password, d.Server, d.Database, d.Charset, d.ParseTime)
}
func main() {
fmt.Println("run main")
}
func init() {
var err error
config := getConfig()
db, err = gorm.Open(config.Db())
if err != nil {
panic(err.Error())
}
db.AutoMigrate(&Account{})
}
func getConfig() Config {
var config Config
_, err := toml.DecodeFile("config.toml", &config)
if err != nil {
panic("unloaded config file")
}
return config
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment