2019-10-04 13:35:33 -04:00
|
|
|
package env
|
|
|
|
|
2019-10-08 01:47:56 -04:00
|
|
|
import (
|
|
|
|
"os"
|
|
|
|
"strings"
|
2019-10-31 02:39:09 -04:00
|
|
|
"sync"
|
2019-10-08 01:47:56 -04:00
|
|
|
)
|
2019-10-04 13:35:33 -04:00
|
|
|
|
2019-10-31 02:39:09 -04:00
|
|
|
var (
|
|
|
|
privateMutex sync.RWMutex
|
|
|
|
envOff bool
|
|
|
|
)
|
|
|
|
|
|
|
|
// SetEnvOff - turns off env lookup
|
|
|
|
func SetEnvOff() {
|
|
|
|
privateMutex.Lock()
|
|
|
|
defer privateMutex.Unlock()
|
|
|
|
|
|
|
|
envOff = true
|
|
|
|
}
|
|
|
|
|
|
|
|
// SetEnvOn - turns on env lookup
|
|
|
|
func SetEnvOn() {
|
|
|
|
privateMutex.Lock()
|
|
|
|
defer privateMutex.Unlock()
|
|
|
|
|
|
|
|
envOff = false
|
|
|
|
}
|
|
|
|
|
2019-10-04 13:35:33 -04:00
|
|
|
// Get retrieves the value of the environment variable named
|
|
|
|
// by the key. If the variable is present in the environment the
|
|
|
|
// value (which may be empty) is returned. Otherwise it returns
|
|
|
|
// the specified default value.
|
|
|
|
func Get(key, defaultValue string) string {
|
2019-10-31 02:39:09 -04:00
|
|
|
privateMutex.RLock()
|
|
|
|
ok := envOff
|
|
|
|
privateMutex.RUnlock()
|
|
|
|
if ok {
|
|
|
|
return defaultValue
|
|
|
|
}
|
2019-10-04 13:35:33 -04:00
|
|
|
if v, ok := os.LookupEnv(key); ok {
|
|
|
|
return v
|
|
|
|
}
|
|
|
|
return defaultValue
|
|
|
|
}
|
|
|
|
|
2019-10-08 01:47:56 -04:00
|
|
|
// List all envs with a given prefix.
|
|
|
|
func List(prefix string) (envs []string) {
|
|
|
|
for _, env := range os.Environ() {
|
|
|
|
if strings.HasPrefix(env, prefix) {
|
2019-10-11 21:21:04 -04:00
|
|
|
values := strings.SplitN(env, "=", 2)
|
|
|
|
if len(values) == 2 {
|
|
|
|
envs = append(envs, values[0])
|
|
|
|
}
|
2019-10-08 01:47:56 -04:00
|
|
|
}
|
|
|
|
}
|
|
|
|
return envs
|
|
|
|
}
|