Skip to content

Instantly share code, notes, and snippets.

@crhntr
Created October 1, 2021 02:53
Show Gist options
  • Save crhntr/58b49404f052dcb5c59e9eca98bc5b87 to your computer and use it in GitHub Desktop.
Save crhntr/58b49404f052dcb5c59e9eca98bc5b87 to your computer and use it in GitHub Desktop.
load config from env
package main
import "reflect"
func loadConfig(data interface{}) {
v := reflect.ValueOf(data)
if v.Kind() != reflect.Ptr || v.Type().Elem().Kind() != reflect.Struct {
panic("expected a pointer to a struct")
}
ve := v.Elem()
vt := ve.Type()
for i := 0; i < vt.NumField(); i++ {
ft := vt.Field(i)
envName := ft.Tag.Get("env")
if envName == "" {
continue
}
envValue := os.Getenv(envName)
if envValue == "" {
continue
}
fv := ve.Field(i)
switch ft.Type.Kind() {
case reflect.String:
fv.SetString(envValue)
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment