@@ -3,11 +3,36 @@ package env
3
3
import (
4
4
"fmt"
5
5
"os"
6
+ "strconv"
6
7
"time"
7
8
)
8
9
10
+ type (
11
+ // Loader interface for loading environment variables
12
+ Loader interface {
13
+ LoadVariable (key string ) (uri string , err error )
14
+ LoadDurationVariable (key string ) (duration time.Duration , err error )
15
+ LoadSecondsVariable (key string ) (seconds float64 , err error )
16
+ LoadIntVariable (key string ) (value int , err error )
17
+ }
18
+
19
+ // DefaultLoader struct
20
+ DefaultLoader struct {}
21
+ )
22
+
23
+ // NewDefaultLoader creates a new default environment variable loader
24
+ func NewDefaultLoader (loadFn func () error ) (* DefaultLoader , error ) {
25
+ // Execute the load function
26
+ if loadFn != nil {
27
+ if err := loadFn (); err != nil {
28
+ return nil , ErrFailedToLoadEnvironmentVariables
29
+ }
30
+ }
31
+ return & DefaultLoader {}, nil
32
+ }
33
+
9
34
// LoadVariable load variable from environment variables
10
- func LoadVariable (key string ) (uri string , err error ) {
35
+ func ( d * DefaultLoader ) LoadVariable (key string ) (uri string , err error ) {
11
36
// Get environment variable
12
37
variable , exists := os .LookupEnv (key )
13
38
if ! exists {
@@ -17,9 +42,12 @@ func LoadVariable(key string) (uri string, err error) {
17
42
}
18
43
19
44
// LoadDurationVariable load duration variable from environment variables
20
- func LoadDurationVariable (key string ) (duration time.Duration , err error ) {
45
+ func (d * DefaultLoader ) LoadDurationVariable (key string ) (
46
+ duration time.Duration ,
47
+ err error ,
48
+ ) {
21
49
// Get environment variable
22
- variable , err := LoadVariable (key )
50
+ variable , err := d . LoadVariable (key )
23
51
if err != nil {
24
52
return 0 , err
25
53
}
@@ -33,11 +61,30 @@ func LoadDurationVariable(key string) (duration time.Duration, err error) {
33
61
}
34
62
35
63
// LoadSecondsVariable load duration variable in seconds from environment variables
36
- func LoadSecondsVariable (key string ) (seconds float64 , err error ) {
64
+ func (d * DefaultLoader ) LoadSecondsVariable (key string ) (
65
+ seconds float64 ,
66
+ err error ,
67
+ ) {
37
68
// Get the duration
38
- duration , err := LoadDurationVariable (key )
69
+ duration , err := d . LoadDurationVariable (key )
39
70
if err != nil {
40
71
return 0 , err
41
72
}
42
73
return duration .Seconds (), nil
43
74
}
75
+
76
+ // LoadIntVariable load integer variable from environment variables
77
+ func (d * DefaultLoader ) LoadIntVariable (key string ) (value int , err error ) {
78
+ // Get environment variable
79
+ variable , err := d .LoadVariable (key )
80
+ if err != nil {
81
+ return 0 , err
82
+ }
83
+
84
+ // Parse the integer
85
+ value , err = strconv .Atoi (variable )
86
+ if err != nil {
87
+ return 0 , fmt .Errorf (ErrInvalidInteger , key , variable )
88
+ }
89
+ return value , nil
90
+ }
0 commit comments