Created
April 15, 2021 09:59
-
-
Save hakur/01a22d523273163e512ddedcca5317ed to your computer and use it in GitHub Desktop.
golang parse environment variable as struct value
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
// first set a env var like SERVER_PORT=8888 | |
var ( | |
Cfg Config | |
) | |
type Config struct { | |
Server Server | |
Clinet Clinet | |
LogLevel string | |
} | |
type Server struct { | |
Port int | |
ListenIP string | |
LogLevel string | |
} | |
type Clinet struct { | |
ServerPort int | |
ServerListenIP string | |
Token string | |
} | |
ParseStructWithEnv(&Cfg, "") | |
println(Cfg.Server.Port) | |
-------------------------------------------------------------------------------------------------- | |
//ParseStructWithEnv 解析struct tag并检测是否存在符合规则的环境变量 如果存在则套用环境变量的值 输入的值必须是指针地址,比如*A而不是**A | |
//ParseStructWithEnv golang parse environment variable as struct value,first parameter must be a pointer struct ,such as *A not **A | |
func ParseStructWithEnv(o interface{}, rootNodeName string) { | |
tp := reflect.TypeOf(o) | |
var val reflect.Value | |
if tp.Kind() == reflect.Ptr { | |
ov := reflect.ValueOf(o) | |
val = reflect.Indirect(ov) | |
} else { | |
val = reflect.ValueOf(o) | |
} | |
for i := 0; i < val.NumField(); i++ { | |
if val.Field(i).Kind() == reflect.Struct { | |
ParseStructWithEnv(val.Field(i).Addr().Interface(), val.Type().Field(i).Name) | |
} else { | |
envName := StrToEnvName(rootNodeName + "_" + val.Type().Field(i).Name) | |
env := os.Getenv(envName) | |
if env == "" { | |
continue | |
} | |
switch val.Field(i).Type().Kind() { | |
case reflect.Bool: | |
v, _ := strconv.ParseBool(env) | |
val.Field(i).SetBool(v) | |
case reflect.Int: | |
v, _ := strconv.ParseInt(env, 10, 64) | |
val.Field(i).SetInt(v) | |
case reflect.String: | |
val.Field(i).SetString(env) | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment