-
Notifications
You must be signed in to change notification settings - Fork 0
/
uri.go
59 lines (50 loc) · 1.23 KB
/
uri.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
package dbi
import (
"os"
)
// URI struct represents parts of connection string
type URI struct {
Username string
Password string
Host string
Port string
Database string
}
// CreateURIFromEnv create URI from environment variables
//
// This should be called after loading environment variables; otherwise, it will create an empty URI
func CreateURIFromEnv() *URI {
user := os.Getenv("PGUSER")
pw := os.Getenv("PGPASSWORD")
host := os.Getenv("PGHOST")
port := os.Getenv("PGPORT")
database := os.Getenv("PGDATABASE")
return &URI{Username: user, Password: pw, Host: host, Port: port, Database: database}
}
// String gives a valid connection string
func (uri *URI) String() string {
var userpw string
var hostport string
var withDB string
// No host
if uri.Host == "" {
return "postgresql://"
}
// username and password
if uri.Username != "" && uri.Password != "" {
userpw = uri.Username + ":" + uri.Password + "@"
} else if uri.Username != "" {
userpw = uri.Username + "@"
}
// host and port
if uri.Port == "" {
hostport = uri.Host
} else {
hostport = uri.Host + ":" + uri.Port
}
// database name
if uri.Database != "" {
withDB = "/" + uri.Database
}
return "postgresql://" + userpw + hostport + withDB
}