41 lines
878 B
Go
41 lines
878 B
Go
package main
|
|
|
|
import (
|
|
"fmt"
|
|
"reflect"
|
|
)
|
|
|
|
func printStructTags(f reflect.Value) {
|
|
for i := 0; i < f.NumField(); i++ {
|
|
field := f.Type().Field(i)
|
|
tag := field.Tag
|
|
fmt.Printf("Field: %v.\nEnvironment variable: %v.\n", field.Name, tag.Get("env"))
|
|
}
|
|
}
|
|
|
|
func setField(obj interface{}, name string, value interface{}) error {
|
|
v := reflect.ValueOf(obj)
|
|
|
|
if v.Kind() != reflect.Ptr || v.Elem().Kind() != reflect.Struct {
|
|
return fmt.Errorf("expected pointer to a struct")
|
|
}
|
|
|
|
v = v.Elem()
|
|
field := v.FieldByName(name)
|
|
|
|
if !field.IsValid() {
|
|
return fmt.Errorf("no such field: %s", name)
|
|
}
|
|
if !field.CanSet() {
|
|
return fmt.Errorf("cannot set field: %s", name)
|
|
}
|
|
|
|
val := reflect.ValueOf(value)
|
|
|
|
if field.Type() != val.Type() {
|
|
return fmt.Errorf("provided value type (%s) doesn't match field type (%s)", val.Type(), field.Type())
|
|
}
|
|
|
|
field.Set(val)
|
|
return nil
|
|
}
|