Created
October 1, 2021 02:53
-
-
Save crhntr/58b49404f052dcb5c59e9eca98bc5b87 to your computer and use it in GitHub Desktop.
load config from env
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 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