-
Notifications
You must be signed in to change notification settings - Fork 0
/
config.go
88 lines (72 loc) · 1.33 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
package main
import (
"bytes"
"os"
"os/exec"
"strconv"
"strings"
)
type cfg struct {
tokens []string
domain string
tls bool
}
func FromEnv() Config {
conf := &cfg{}
conf.tokens = getEnvValCSV("COWSAY_TOKENS")
conf.domain = getEnvVal("COWSAY_TLS_DOMAIN")
conf.tls = getEnvVal("COWSAY_AUTO_TLS") == "TRUE"
return conf
}
func (c *cfg) Tokens() []string {
return c.tokens
}
func (c *cfg) CowsayExec() string {
uri, err := whichCowsay()
if err != nil {
return DefaultCowsay
}
return uri
}
func (c *cfg) Domain() string {
return c.domain
}
func (c *cfg) TLS() bool {
return c.tls
}
func whichCowsay() (string, error) {
cmd := exec.Command("which", "cowsay")
var out bytes.Buffer
cmd.Stdout = &out
err := cmd.Run()
if err != nil {
return "", err
}
return strings.TrimRight(out.String(), "\n"), nil
}
type Config interface {
Tokens() []string
CowsayExec() string
Domain() string
TLS() bool
}
func getEnvValCSV(envVars ...string) []string {
str := getEnvVal(envVars...)
if str == "" {
return nil
}
return strings.Split(str, ",")
}
func getEnvValInt(envVars ...string) (int, error) {
str := getEnvVal(envVars...)
val, err := strconv.Atoi(str)
return val, err
}
func getEnvVal(envVars ...string) string {
for _, envVar := range envVars {
if v := os.Getenv(envVar); v != "" {
return v
}
}
return ""
}