forked from zhanggf2010/v2ray-ssrpanel-plugin
-
Notifications
You must be signed in to change notification settings - Fork 0
/
mysql.go
56 lines (46 loc) · 1.17 KB
/
mysql.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
51
52
53
54
55
56
package ssrpanel
import (
"fmt"
"github.com/go-sql-driver/mysql"
"github.com/jinzhu/gorm"
_ "github.com/jinzhu/gorm/dialects/mysql"
"time"
)
type MySQLConfig struct {
Host string `json:"host"`
Port int `json:"port"`
User string `json:"user"`
Password string `json:"password"`
DBName string `json:"dbname"`
}
func (c *MySQLConfig) FormatDSN() (string, error) {
loc, err := time.LoadLocation("Asia/Shanghai")
if err != nil {
return "", err
}
cc := &mysql.Config{
Collation: "utf8mb4_unicode_ci",
User: c.User,
Passwd: c.Password,
Loc: loc,
DBName: c.DBName,
Net: "tcp",
Addr: fmt.Sprintf("%s:%d", c.Host, c.Port),
AllowNativePasswords: true,
}
return cc.FormatDSN(), nil
}
func NewMySQLConn(config *MySQLConfig) (*DB, error) {
newError("Connecting database...").AtInfo().WriteToLog()
dsn, err := config.FormatDSN()
if err != nil {
return nil, err
}
db, err := gorm.Open("mysql", dsn)
if err != nil {
return nil, err
}
db.SingularTable(true)
defer newError("Connected").AtInfo().WriteToLog()
return &DB{DB: db}, nil
}