-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathdatabase.go
50 lines (42 loc) · 1.03 KB
/
database.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
package database
import (
"echo_shop/bootstrap/config"
"fmt"
"log"
_ "github.com/go-sql-driver/mysql" // mysql
"github.com/jinzhu/gorm"
)
var dbClient *gorm.DB
// InitDB 初始化 db
func InitDB() {
url := createDBURL(
config.String("DB.USERNAME"),
config.String("DB.PASSWORD"),
config.String("DB.HOST"),
config.String("DB.PORT"),
dbname(),
)
db, err := gorm.Open(config.String("DB.CONNECTION"), url)
if err != nil {
log.Fatal("Database connection failed. Database url: "+url+" error: ", err)
}
db.LogMode(config.IsDev())
dbClient = db
}
// DBManager 获取
func DBManager() *gorm.DB {
if dbClient == nil {
panic("请先初始化 InitDB")
}
return dbClient
}
func createDBURL(uname string, pwd string, host string, port string, dbname string) string {
return fmt.Sprintf("%s:%s@tcp(%s:%s)/%s?charset=utf8&parseTime=%t&loc=%s",
uname, pwd,
host, port,
dbname, true, "Local")
}
func dbname() string {
// name_debug name_release name_test
return config.String("DB.DATABASE") + "_" + config.String("APP.RUNMODE")
}