-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathconfig.go
82 lines (68 loc) · 1.32 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
package psqlx
import (
"errors"
"fmt"
"os"
"regexp"
)
type Config struct {
Network string
Host string
Port string
Username string
Password string
Database string
}
var rx = regexp.MustCompile(`postgres:\/\/(.*):(.*)@(.*):(\d+)\/(.*)\?sslmode=disable`)
func (c *Config) LoadFromStr(dsn string) error {
sub := rx.FindStringSubmatch(dsn)
if len(sub) != 6 {
return errors.New("invalid connection string")
}
c.Network = "tcp"
c.Host = sub[3]
c.Port = sub[4]
c.Username = sub[1]
c.Password = sub[2]
c.Database = sub[5]
return nil
}
func (c *Config) LoadFromEnv() {
c.Network = os.Getenv("DB_NETWORK")
if c.Network == "" {
c.Network = "tcp"
}
c.Host = os.Getenv("DB_HOST")
if c.Host == "" {
c.Host = "db"
}
c.Port = os.Getenv("DB_PORT")
if c.Port == "" {
c.Port = "5432"
}
c.Username = os.Getenv("DB_USERNAME")
if c.Username == "" {
c.Username = "postgres"
}
c.Password = os.Getenv("DB_PASSWORD")
if c.Password == "" {
c.Password = "postgres"
}
c.Database = os.Getenv("DB_DATABASE")
if c.Database == "" {
c.Database = "postgres"
}
}
func (c *Config) DSN() string {
return fmt.Sprintf(
"postgres://%s:%s@%s:%s/%s?sslmode=disable",
c.Username,
c.Password,
c.Host,
c.Port,
c.Database,
)
}
func (c *Config) Address() string {
return fmt.Sprintf("%s:%s", c.Host, c.Port)
}