Created
October 24, 2022 08:43
-
-
Save hauxe/05db84cc21ac1c0af66be32dcf2b416e to your computer and use it in GitHub Desktop.
Generic get environment
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package utils | |
import ( | |
"os" | |
"strconv" | |
) | |
type Env[T any] struct { | |
DefaultVal T | |
FromString func(string) (T, error) | |
} | |
var EnvString = Env[string]{ | |
DefaultVal: "", | |
FromString: func(s string) (string, error) { return s, nil }, | |
} | |
var EnvInt = Env[int]{ | |
DefaultVal: 0, | |
FromString: strconv.Atoi, | |
} | |
var EnvBool = Env[bool]{ | |
DefaultVal: false, | |
FromString: strconv.ParseBool, | |
} | |
// GetEnvT get env value of T type | |
func GetEnvT[T any](name string, e Env[T]) T { | |
v := os.Getenv(name) | |
if v == "" { | |
return e.DefaultVal | |
} | |
d, err := e.FromString(v) | |
if err != nil { | |
return e.DefaultVal | |
} | |
return d | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment