This repository has been archived by the owner on May 18, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 2
/
environment_source.go
72 lines (58 loc) · 1.93 KB
/
environment_source.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
package configo
import (
"os"
"strings"
"unicode"
)
// EnvironmentSource reads key-value pairs from the environment.
type EnvironmentSource struct {
prefix string
separator string
}
// FromEnvironment creates an environment source capable of
// parsing values separated by the pipe character.
func FromEnvironment() *EnvironmentSource {
return FromEnvironmentCustomSeparator("", "|")
}
// FromEnvironmentWithPrefix creates an environment source capable of:
// - reading values with keys all beginning with the provided prefix,
// - parsing values separated by the pipe character.
func FromEnvironmentWithPrefix(prefix string) *EnvironmentSource {
return FromEnvironmentCustomSeparator(prefix, "|")
}
// FromEnvironmentCustomSeparator creates an environment source capable of
// parsing values separated by the specified character.
func FromEnvironmentCustomSeparator(prefix, separator string) *EnvironmentSource {
return &EnvironmentSource{prefix: prefix, separator: separator}
}
// Strings reads the environment variable specified by key and returns the value or ErrKeyNotFound.
func (this *EnvironmentSource) Strings(key string) ([]string, error) {
key = this.prefix + sanitizeKey(key)
if value := os.Getenv(key); len(value) > 0 {
return strings.Split(value, this.separator), nil
}
if value := os.Getenv(strings.ToUpper(key)); len(value) > 0 {
return strings.Split(value, this.separator), nil
}
if value := os.Getenv(strings.ToLower(key)); len(value) > 0 {
return strings.Split(value, this.separator), nil
}
return nil, ErrKeyNotFound
}
func sanitizeKey(key string) string {
if strings.HasPrefix(key, "env:") {
key = key[len("env:"):]
}
sanitized := ""
for _, character := range key {
if unicode.IsDigit(character) {
sanitized += string(character)
} else if unicode.IsLetter(character) {
sanitized += string(character)
} else {
sanitized += "_"
}
}
return sanitized
}
func (this *EnvironmentSource) Initialize() {}