Skip to content

Commit 5331187

Browse files
committed
feat: Added LoadDurationVariable and LoadSecondsVariable functions
1 parent 7b4328a commit 5331187

File tree

2 files changed

+28
-0
lines changed

2 files changed

+28
-0
lines changed

env/errors.go

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,4 +5,5 @@ import "errors"
55
var (
66
EnvironmentVariableNotFoundError = "environment variable not found: %v"
77
FailedToLoadEnvironmentVariablesError = errors.New("failed to load environment variables")
8+
InvalidDurationError = "invalid key '%v' duration value: %v"
89
)

env/loader.go

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@ package env
33
import (
44
"fmt"
55
"os"
6+
"time"
67
)
78

89
// LoadVariable load variable from environment variables
@@ -14,3 +15,29 @@ func LoadVariable(key string) (uri string, err error) {
1415
}
1516
return variable, nil
1617
}
18+
19+
// LoadDurationVariable load duration variable from environment variables
20+
func LoadDurationVariable(key string) (duration time.Duration, err error) {
21+
// Get environment variable
22+
variable, err := LoadVariable(key)
23+
if err != nil {
24+
return 0, err
25+
}
26+
27+
// Parse the duration
28+
duration, err = time.ParseDuration(variable)
29+
if err != nil {
30+
return 0, fmt.Errorf(InvalidDurationError, key, variable)
31+
}
32+
return duration, nil
33+
}
34+
35+
// LoadSecondsVariable load duration variable in seconds from environment variables
36+
func LoadSecondsVariable(key string) (seconds float64, err error) {
37+
// Get the duration
38+
duration, err := LoadDurationVariable(key)
39+
if err != nil {
40+
return 0, err
41+
}
42+
return duration.Seconds(), nil
43+
}

0 commit comments

Comments
 (0)