if v, ok := os.LookupEnv("IDAASHTTPPORT"); ok {
c.HTTPPort, _ = strconv.Atoi(v)
}
if v, ok := os.LookupEnv("IDAASDBNAME"); ok {
c.DBUserName = v
}
if v, ok := os.LookupEnv("IDAASDBPW"); ok {
c.DBPasswd = v
}
if v, ok := os.LookupEnv("IDAASDBPORT"); ok {
c.DBPort, _ = strconv.Atoi(v)
}
if v, ok := os.LookupEnv("IDAASDBHOST"); ok {
c.DBHost = v
}
'c' is the following struct
type Configuration struct {
HTTPPort int
DBUserName string
DBPasswd string
DBPort int
DBHost string
}
I only want to update the struct field if the environment variable exists. Seems like some little cute map iterator or something like that would work, but I can't figure out a nice solution.
You can use some helper functions:
func setIntFromEnv(val *int, envName string) {
if v, ok := os.LookupEnv(envName); ok {
*val, _ = strconv.Atoi(v)
}
}
func setStringFromEnv(val *string, envName string) {
if v, ok := os.LookupEnv(envName); ok {
*val = v
}
}
// From your main function.
setIntFromEnv(&c.HTTPPort, "IDAASHTTPPORT")
setStringFromEnv(&c.DBUserName, "IDAASDBNAME")
etc...
This only works if you're ok ignoring a string env var that you're trying to parse as an int. Its relative elegance is also debatable.