@@ -3,11 +3,36 @@ package env
33import (
44 "fmt"
55 "os"
6+ "strconv"
67 "time"
78)
89
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+
934// 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 ) {
1136 // Get environment variable
1237 variable , exists := os .LookupEnv (key )
1338 if ! exists {
@@ -17,9 +42,12 @@ func LoadVariable(key string) (uri string, err error) {
1742}
1843
1944// 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+ ) {
2149 // Get environment variable
22- variable , err := LoadVariable (key )
50+ variable , err := d . LoadVariable (key )
2351 if err != nil {
2452 return 0 , err
2553 }
@@ -33,11 +61,30 @@ func LoadDurationVariable(key string) (duration time.Duration, err error) {
3361}
3462
3563// 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+ ) {
3768 // Get the duration
38- duration , err := LoadDurationVariable (key )
69+ duration , err := d . LoadDurationVariable (key )
3970 if err != nil {
4071 return 0 , err
4172 }
4273 return duration .Seconds (), nil
4374}
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