-
Notifications
You must be signed in to change notification settings - Fork 0
/
db_handler.go
51 lines (43 loc) · 971 Bytes
/
db_handler.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 infra
import (
"fmt"
"log"
"os"
_ "time/tzdata"
"gorm.io/driver/mysql"
"gorm.io/gorm"
)
type DBHandler struct {
DB *gorm.DB
}
func NewDBHandler() *DBHandler {
user := os.Getenv("MYSQL_USER")
password := os.Getenv("MYSQL_PASSWORD")
host := os.Getenv("MYSQL_HOST")
port := os.Getenv("MYSQL_PORT")
dbName := os.Getenv("DATABASE_NAME")
dsn := fmt.Sprintf(
"%s:%s@tcp(%s:%s)/%s?charset=utf8mb4&parseTime=True&loc=%s",
user, password, host, port, dbName, "Asia%2FTokyo",
)
db, err := gorm.Open(mysql.Open(dsn), &gorm.Config{})
if err != nil {
log.Panic(err)
}
return &DBHandler{DB: db}
}
func (h *DBHandler) Find(dest interface{}, conds ...interface{}) (err error) {
result := new(gorm.DB)
if len(conds) == 0 {
result = h.DB.Find(dest)
} else {
result = h.DB.Find(dest, conds)
}
err = result.Error
return
}
func (h *DBHandler) Create(value interface{}) (err error) {
result := h.DB.Create(value)
err = result.Error
return
}