Skip to content

Instantly share code, notes, and snippets.

@hauxe
Created October 24, 2022 08:43
Show Gist options
  • Save hauxe/05db84cc21ac1c0af66be32dcf2b416e to your computer and use it in GitHub Desktop.
Save hauxe/05db84cc21ac1c0af66be32dcf2b416e to your computer and use it in GitHub Desktop.
Generic get environment
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