-
Notifications
You must be signed in to change notification settings - Fork 10
/
environment.go
76 lines (62 loc) · 1.87 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
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
package configure
import (
"errors"
"os"
"strconv"
"strings"
)
// NewEnvironment creates a new instance of the Environment Checker.
// Note: If you request a value "peanut-butter", the environment variable that will be checked is `PEANUT_BUTTER`.
func NewEnvironment() *Environment {
return &Environment{}
}
// Environment is a Checker. It retrieves values from the host OS's environment variables.
// In this process, it will take a flag-like name, and convert it to a environmnet-like name. The process
// for this is to change all characters to upper case, and then replace hyphons with underscores.
type Environment struct {
}
func (e Environment) Setup() error {
return nil
}
// value takes a string in normal flag syntax (hello-world) and changes
// it into a environment variable syntax (HELLO_WORLD). It returns the
// the value associated with that env.
func (e Environment) value(name string) (string, error) {
n := e.process(name)
v := os.Getenv(n)
if v == "" {
return v, errors.New("Value does not exist")
}
return v, nil
}
func (e Environment) process(name string) string {
// name is in form hello-world
// we need it in form HELLO_WORLD
name = strings.ToUpper(name)
name = strings.Replace(name, "-", "_", -1)
return name
}
// Int returns an int if it exists in the set environment variables.
func (e Environment) Int(name string) (int, error) {
v, err := e.value(name)
if err != nil {
return 0, err
}
i, err := strconv.Atoi(v)
if err != nil {
return 0, err
}
return i, nil
}
// Bool returns a bool if it exists in the set environment variables.
func (e *Environment) Bool(name string) (bool, error) {
v, err := e.value(name)
if err != nil {
return false, err
}
return strconv.ParseBool(v)
}
// String returns a string if it exists in the set environment variables.
func (e Environment) String(name string) (string, error) {
return e.value(name)
}