Skip to content

Commit

Permalink
Add env defaulting funcs to operatorpkg
Browse files Browse the repository at this point in the history
  • Loading branch information
jonathan-innis committed Feb 8, 2025
1 parent 5fbad4f commit 673a66a
Showing 1 changed file with 73 additions and 0 deletions.
73 changes: 73 additions & 0 deletions env/env.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,73 @@
package env

import (
"os"
"strconv"
"time"
)

// WithDefaultInt returns the int value of the supplied environment variable or, if not present,
// the supplied default value. If the int conversion fails, returns the default
func WithDefaultInt(key string, def int) int {
val, ok := os.LookupEnv(key)
if !ok {
return def
}
i, err := strconv.Atoi(val)
if err != nil {
return def
}
return i
}

// WithDefaultInt64 returns the int value of the supplied environment variable or, if not present,
// the supplied default value. If the int conversion fails, returns the default
func WithDefaultInt64(key string, def int64) int64 {
val, ok := os.LookupEnv(key)
if !ok {
return def
}
i, err := strconv.ParseInt(val, 10, 64)
if err != nil {
return def
}
return i
}

// WithDefaultString returns the string value of the supplied environment variable or, if not present,
// the supplied default value.
func WithDefaultString(key string, def string) string {
val, ok := os.LookupEnv(key)
if !ok {
return def
}
return val
}

// WithDefaultBool returns the boolean value of the supplied environment variable or, if not present,
// the supplied default value.
func WithDefaultBool(key string, def bool) bool {
val, ok := os.LookupEnv(key)
if !ok {
return def
}
parsedVal, err := strconv.ParseBool(val)
if err != nil {
return def
}
return parsedVal
}

// WithDefaultDuration returns the duration value of the supplied environment variable or, if not present,
// the supplied default value.
func WithDefaultDuration(key string, def time.Duration) time.Duration {
val, ok := os.LookupEnv(key)
if !ok {
return def
}
parsedVal, err := time.ParseDuration(val)
if err != nil {
return def
}
return parsedVal
}

0 comments on commit 673a66a

Please sign in to comment.