diff --git a/string_utils/key_reader.go b/string_utils/key_reader.go new file mode 100644 index 0000000000000000000000000000000000000000..5d2bf3052c4d0c2ba91a58a3553dba82e5f74c45 --- /dev/null +++ b/string_utils/key_reader.go @@ -0,0 +1,39 @@ +package string_utils + +import ( + "os" + "strings" +) + +//KeyReader is an interface to read string "<key>":"<value>" pairs +//which is common to read from the environment +//it is abstracted so the same interface can be implemented for +//reading for example from REDIS and other sources +type KeyReader interface { + Keys(prefix string) []string + GetString(key string) (value string, ok bool) +} + +func EnvironmentKeyReader() KeyReader { + return envKeyReader{} +} + +type envKeyReader struct{} + +func (envKeyReader) GetString(key string) (value string, ok bool) { + value = os.Getenv(key) + if value == "" { + return "", false + } + return value, true +} + +func (envKeyReader) Keys(prefix string) []string { + keys := []string{} + for _, env := range os.Environ() { + if strings.HasPrefix(env, prefix) { + keys = append(keys, strings.SplitN(env, "=", 2)[0]) + } + } + return keys +}