Skip to content

Instantly share code, notes, and snippets.

@imedadel
Created September 23, 2022 21:33
Show Gist options
  • Save imedadel/2ee35e4385d4fc59eb1ff579ca6ca950 to your computer and use it in GitHub Desktop.
Save imedadel/2ee35e4385d4fc59eb1ff579ca6ca950 to your computer and use it in GitHub Desktop.
Generic function to load and parse environment variable in Go
func getEnv[T int | string | bool](str string) T {
env, ok := os.LookupEnv(str)
if !ok {
log.Fatalf("%s environment variable required but not set", str)
}
var v T
switch t := any(&v).(type) {
case *string:
*t = env
case *int:
i, err := strconv.Atoi(env)
if err != nil {
log.Fatal(err)
}
*t = int(i)
case *bool:
b, err := strconv.ParseBool(env)
if err != nil {
log.Fatal(err)
}
*t = bool(b)
}
return v
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment