/
options.go
75 lines (63 loc) · 1.72 KB
/
options.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 sync
import (
"os"
"strings"
)
// Engine is a type of PubSub engine.
type Engine string
const (
// EngineRedis is the redis engine.
EngineRedis Engine = "redis"
)
const (
// EnvPubSubAddresses is the environment variable name for the addresses.
// Addresses are separated by colons (ie the `:` symbol).
EnvPubSubAddresses = "PUBSUB_ADDRESSES"
// EnvPubSubUsername is the environment variable name for the username
EnvPubSubUsername = "PUBSUB_USERNAME"
// EnvPubSubPassword is the environment variable name for the password
EnvPubSubPassword = "PUBSUB_PASSWORD"
// EnvPubSubEngine is the environment variable name for the engine
EnvPubSubEngine = "PUBSUB_ENGINE"
)
var (
// defaultAddress is a map of default addresses for each engine.
defaultAddress = map[Engine]string{
EngineRedis: "localhost:6379",
}
)
// Options holds generic options for connecting to something
type Options struct {
Engine Engine
Addresses []string
Username string
Password string
}
// NewOptions returns a new Options struct.
// We read default variables from the environment.
// - If not given we default to redis.
// - If no addresses are given we default to localhost.
func NewOptions() *Options {
eng := Engine(os.Getenv(EnvPubSubEngine))
if eng == "" {
eng = EngineRedis
}
addresses := []string{}
for _, address := range strings.Split(os.Getenv(EnvPubSubAddresses), ":") {
if address != "" {
addresses = append(addresses, address)
}
}
if len(addresses) == 0 {
defaultAddr, ok := defaultAddress[eng]
if ok {
addresses = append(addresses, defaultAddr)
}
}
return &Options{
Engine: eng,
Addresses: addresses,
Username: os.Getenv(EnvPubSubUsername),
Password: os.Getenv(EnvPubSubPassword),
}
}