beegoinit/db/db.go
2020-07-02 15:59:04 +08:00

71 lines
1.3 KiB
Go

package db
import (
"fmt"
_ "github.com/go-sql-driver/mysql"
_ "github.com/lib/pq"
"golib.gaore.com/GaoreGo/grconfig"
"golib.gaore.com/GaoreGo/grlogs"
)
const DEFAULT = "default"
var DbPrefix map[string]string = make(map[string]string)
type dsnConfig struct {
Dsn string
Driver string
Item *DbItem
}
type DbItem struct {
User string `yaml:"user"`
Pass string `yaml:"pass"`
Host string `yaml:"host"`
Port int `yaml:"port"`
Name string `yaml:"name"`
Driver string `yaml:"driver"`
Prefix string `yaml:"prefix"`
}
func (d *DbItem) Dsn() string {
return fmt.Sprintf("%s:%s@tcp(%s:%d)/%s?charset=utf8&loc=Local&autocommit=true&timeout=5s", d.User, d.Pass, d.Host, d.Port, d.Name)
}
func init() {
var err error
logger := grlogs.GetAli("sql")
defer func() {
if err != nil {
logger.Critical(err.Error())
}
}()
dsns, err := GetDsn()
if err = LoadXorm(dsns); err != nil {
logger.Critical(err.Error())
}
}
func GetDsn() (DsnList map[string]dsnConfig, err error) {
var items map[string]*DbItem
DsnList = make(map[string]dsnConfig)
configer := grconfig.New("conf/")
err = configer.Item("db", &items)
if err != nil {
return
}
for alias, v := range items {
dsn := v.Dsn()
driver := v.Driver
if driver == "" {
driver = "mysql"
}
DsnList[alias] = dsnConfig{Dsn: dsn, Driver: driver, Item: v}
}
return
}