-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathconnectionstring.go
58 lines (47 loc) · 1.37 KB
/
connectionstring.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
package mysqlkebab
import (
"fmt"
"os"
"strings"
)
// ConnectionString has directives to obtain database connection string
// To create a new ConnectionString, use ConnStringDirect(), ConnStringEnvVar()
type ConnectionString struct {
method csMethod
key string
value string
}
func (s ConnectionString) validate() error {
if s.method == csMethodDirectParam && s.value == "" {
return fmt.Errorf(`connection string declared as "direct param", but value field empty`)
}
if s.method == csMethodEnvVariable {
if s.key == "" {
return fmt.Errorf(`connection string declared as "environment variable", but key field is empty`)
}
val := os.Getenv(s.key)
if val == "" {
return fmt.Errorf(`connection string declared as "environment variable", but the given key doesn't exist or is empty`)
}
s.value = val
}
return nil
}
func (s ConnectionString) get() string {
return s.value
}
// ConnStringDirect sets connection string with given value
func ConnStringDirect(val string) *ConnectionString {
return &ConnectionString{
method: csMethodDirectParam,
value: strings.TrimSpace(val),
}
}
// ConnStringEnvVar configures the engine to obtain connection string from given environment variable
func ConnStringEnvVar(key string) *ConnectionString {
return &ConnectionString{
method: csMethodEnvVariable,
key: strings.TrimSpace(key),
value: os.Getenv(key),
}
}