-
Notifications
You must be signed in to change notification settings - Fork 0
/
config.go
100 lines (87 loc) · 2.46 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
89
90
91
92
93
94
95
96
97
98
99
100
package cyfe
import (
"fmt"
"os"
"strings"
"time"
"github.com/spf13/viper"
)
var config = &configStruct{}
type configStruct struct {
environment string
cyfeRoot string
metricLookups []metricLookup
timezone *time.Location
}
type metricLookup struct {
Metric string
Token string
}
func init() {
setup()
}
func isProd() (isProd bool) {
if config.environment == "production" {
isProd = true
}
return
}
func setup() (err error) {
// setup the application; this is broken out from the init()
// so that it may be called by unit tests to change env vars
config.environment = strings.ToLower(os.Getenv("CYFE_ENV"))
if config.environment == "" {
config.environment = "dev"
}
config.cyfeRoot = "https://app.cyfe.com/api/push/"
config.metricLookups = []metricLookup{}
// set the timezone, since the Push API will expect dates in a specific tmezone
loc, err := time.LoadLocation(os.Getenv("CYFE_TIMEZONE"))
if err != nil {
loc, _ = time.LoadLocation("UTC")
}
config.timezone = loc
// each push to the API requires a chart token. The specific metric to specific chart
// can come from the file (CYFE_TOKEN_FILE) or can come from the environment
// (looping over all CYFE_TOKEN_* environment variables)
// this should only be created during initialization
// file first
fileLocation := os.Getenv("CYFE_TOKEN_FILE")
if fileLocation != "" {
viper.AddConfigPath(".")
viper.SetConfigName(fileLocation)
err := viper.ReadInConfig()
if err != nil {
// the user said to find a file, but we couldn't so we error out
// of course, panicking in an included library is bad, so just output a warning
// and hope they see it
// TODO: integrate logrus here
err = fmt.Errorf("ERROR: CYFE_TOKEN_FILE named but not found")
fmt.Println(err.Error())
return err
}
parsed := []metricLookup{}
err = viper.UnmarshalKey("metric", &parsed)
if err != nil || len(parsed) == 0 {
// the config could not be parsed
err = fmt.Errorf("ERROR: CYFE_TOKEN_FILE could not be parsed")
fmt.Println(err.Error())
return err
}
config.metricLookups = parsed
}
// TODO: do we want to consider a default toml file?
// now the env
env := os.Environ()
for i := range env {
if strings.HasPrefix(env[i], "CYFE_TOKEN") {
split := strings.Split(env[i], "=")
metric := strings.TrimPrefix(split[0], "CYFE_TOKEN_")
config.metricLookups = append(config.metricLookups, metricLookup{
Metric: metric,
Token: split[1],
})
}
}
return nil
}