💻 Tech
Go’s reflect package is a powerful package as it allows you to inspect a variable’s type and value at runtime. For example, the code below gets the struct tag env value from a struct:
type xType struct {
A string `env:"A"`
B string `env:"B"`
}
x := xType{}
v := reflect.ValueOf(env).Elem() // Get the value of the struct
for i := 0; i < v.NumField(); i++ {
field := v.Type().Field(i) // Get the field
tag := field.Tag.Get("env") // Get the tag
fmt.Println(tag) // Prints A and B, which are the values of the env tags
}