forked from Missuo0o/BankSystemBackend
-
Notifications
You must be signed in to change notification settings - Fork 0
/
dbConfig.go
51 lines (44 loc) · 1.01 KB
/
dbConfig.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
package main
import (
"fmt"
"log"
"os"
"gopkg.in/yaml.v3"
_ "gopkg.in/yaml.v3"
"gorm.io/driver/mysql"
"gorm.io/gorm"
)
type Set struct {
DBConf DBConf `yaml:"db"`
// AppConf AppConf `yaml:"app"`
}
type DBConf struct {
Host string `yaml:"host"`
Port string `yaml:"port"`
User string `yaml:"username"`
Password string `yaml:"password"`
DBName string `yaml:"dbname"`
}
func (conf *Set) getConf() *Set {
yamlFile, err := os.ReadFile("config.yaml")
if err != nil {
log.Fatalf("yamlFile.Get err #%v ", err)
}
err = yaml.Unmarshal(yamlFile, &conf)
if err != nil {
log.Fatalf("Unmarshal: %v", err)
}
return conf
}
func connectDB() (*gorm.DB, error) {
var set Set
set.getConf()
fmt.Println(set)
var dbConf = set.DBConf
dsn := dbConf.User + ":" + dbConf.Password + "@tcp(" + dbConf.Host + ":" + dbConf.Port + ")/" + dbConf.DBName + "?charset=utf8mb4&parseTime=True&loc=Local"
db, err := gorm.Open(mysql.Open(dsn), &gorm.Config{})
if err != nil {
return nil, err
}
return db, nil
}