-
Notifications
You must be signed in to change notification settings - Fork 3
/
config.go
104 lines (77 loc) · 1.63 KB
/
config.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
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
package sql
import (
"fmt"
"net/url"
"time"
types "github.com/kilnfi/go-utils/common/types"
)
type Config struct {
Dialect string
User string
Password string
Host string
Port uint16
DBName string
SSLMode, SSLCert, SSLKey, SSLCA string
ConnectTimeout *types.Duration
PoolSize int
KeepAlive *types.Duration
GormLoggerOff bool
}
var pgDialect = "postgres"
func (cfg *Config) SetDefault() *Config {
if cfg.Dialect == "" {
cfg.Dialect = pgDialect
}
if cfg.User == "" {
cfg.User = pgDialect
}
if cfg.Password == "" {
cfg.Password = pgDialect
}
if cfg.Host == "" {
cfg.Host = "localhost"
}
if cfg.Port == 0 {
cfg.Port = uint16(5432)
}
if cfg.DBName == "" {
cfg.DBName = pgDialect
}
if cfg.SSLMode == "" {
cfg.SSLMode = "disable"
}
if cfg.ConnectTimeout == nil {
cfg.ConnectTimeout = &types.Duration{Duration: 30 * time.Second}
}
if cfg.KeepAlive == nil {
cfg.KeepAlive = &types.Duration{Duration: time.Minute}
}
return cfg
}
func (cfg *Config) DSN() *url.URL {
u := &url.URL{
Scheme: cfg.Dialect,
Host: fmt.Sprintf("%v:%v", cfg.Host, cfg.Port),
User: url.UserPassword(cfg.User, cfg.Password),
Path: cfg.DBName,
}
query := make(url.Values)
if cfg.ConnectTimeout != nil {
query.Add("connect_timeout", fmt.Sprintf("%v", int64(cfg.ConnectTimeout.Duration/time.Second)))
}
if cfg.SSLCA != "" {
query.Add("sslrootcert", cfg.SSLCA)
}
if cfg.SSLKey != "" {
query.Add("sslkey", cfg.SSLKey)
}
if cfg.SSLCert != "" {
query.Add("sslcert", cfg.SSLCert)
}
if cfg.SSLMode != "" {
query.Add("sslmode", cfg.SSLMode)
}
u.RawQuery = query.Encode()
return u
}