-
Notifications
You must be signed in to change notification settings - Fork 0
/
environment.go
49 lines (40 loc) · 1.06 KB
/
environment.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
package config
import (
"encoding/json"
)
// Getter takes an environment variable name, and returns its
// value or "" if not set.
type Getter func(string) string
// ConfigEnvironmentVariable is the expected environment variable
// storing JSON configuration data.
const ConfigEnvironmentVariable = "CONFIG"
// FromEnvironment unmarshals JSON configuration from the CONFIG
// environment variable into dst.
func FromEnvironment(get Getter, dst any) error {
if env := get(ConfigEnvironmentVariable); env != "" {
err := json.Unmarshal([]byte(env), dst)
if err != nil {
return err
}
}
return nil
}
// EnvironmentName returns the name of the current execution environment
// from CONFIG. If no environment is detected, "local" is returned.
func EnvironmentName(get Getter) string {
config := get(ConfigEnvironmentVariable)
if config == "" {
return "local"
}
cfg := struct {
Env string `json:"env"`
}{}
err := json.Unmarshal([]byte(config), &cfg)
if err != nil {
panic(err)
}
if cfg.Env == "" {
panic("no `env` field in CONFIG")
}
return cfg.Env
}