/
service.go
75 lines (62 loc) · 1.69 KB
/
service.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
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
package database
import (
"fmt"
"github.com/pkg/errors"
"gorm.io/driver/mysql"
"gorm.io/gorm"
gormlog "gorm.io/gorm/logger"
"github.com/68696c6c/goat/sys/log"
)
type Config struct {
Debug bool
Host string
Port int
Database string
Username string
Password string
}
func (c Config) String() string {
return fmt.Sprintf("Host: %v, Port: %v, Database: %v, Username: %v, Password: %v, Debug: %v", c.Host, c.Port, c.Database, c.Username, c.Password, c.Debug)
}
func (c Config) ConnectionString() string {
return fmt.Sprintf("%s:%s@tcp(%s:%d)/%s?charset=utf8mb4&parseTime=true", c.Username, c.Password, c.Host, c.Port, c.Database)
}
type Service interface {
GetMainDB() (*gorm.DB, error)
GetConnection(c Config) (*gorm.DB, error)
}
func NewService(c Config, l log.Service) Service {
return service{
config: c,
dialect: "mysql",
log: l,
}
}
type service struct {
config Config
dialect string
log log.Service
}
// GetMainDB returns a new database connection using the configured defaults.
func (s service) GetMainDB() (*gorm.DB, error) {
connection, err := s.GetConnection(s.config)
if err != nil {
msg := fmt.Sprintf("failed to connect to default database using credentials: %s", s.config.String())
return nil, errors.Wrap(err, msg)
}
return connection, nil
}
// GetConnection returns a database connection using the provided configuration.
func (s service) GetConnection(c Config) (*gorm.DB, error) {
logLevel := gormlog.Error
if c.Debug {
logLevel = gormlog.Info
}
connection, err := gorm.Open(mysql.Open(c.ConnectionString()), &gorm.Config{
Logger: s.log.GormLogger().LogMode(logLevel),
})
if err != nil {
return nil, err
}
return connection, nil
}