github.com/cidverse/cid-sdk-go@v0.0.0-20240318001225-c193d83f053e/env-tag.go (about) 1 package cidsdk 2 3 import ( 4 "os" 5 "reflect" 6 "strconv" 7 ) 8 9 const envVarTag = "env" 10 11 // OverwriteFromEnv will overwrite values with the given env values if present 12 func OverwriteFromEnv(data interface{}) { 13 val := reflect.ValueOf(data).Elem() 14 t := val.Type() 15 16 // check if the type passed in is a struct 17 if t.Kind() != reflect.Struct { 18 return 19 } 20 21 // iterate over all fields of the struct 22 for i := 0; i < t.NumField(); i++ { 23 field := t.Field(i) 24 25 tag := field.Tag.Get(envVarTag) 26 if tag == "" { 27 continue 28 } 29 if envVal, isSet := os.LookupEnv(tag); isSet { 30 fieldVal := val.Field(i) 31 switch fieldVal.Kind() { 32 case reflect.String: 33 fieldVal.SetString(envVal) 34 case reflect.Int: 35 valAsInt, _ := strconv.Atoi(envVal) 36 fieldVal.Set(reflect.ValueOf(valAsInt)) 37 case reflect.Bool: 38 valAsBool, _ := strconv.ParseBool(envVal) 39 fieldVal.Set(reflect.ValueOf(valAsBool)) 40 default: 41 // unsupported type 42 } 43 } 44 } 45 }