1
0
mirror of https://github.com/taigrr/wtf synced 2025-01-18 04:03:14 -08:00

WTF-986 Extract the reflection bits into a Reflective package

Signed-off-by: Chris Cummer <chriscummer@me.com>
This commit is contained in:
Chris Cummer
2020-10-13 21:08:24 -07:00
parent 07f4d3f524
commit 356a998404
3 changed files with 48 additions and 43 deletions

25
utils/reflective.go Normal file
View File

@@ -0,0 +1,25 @@
package utils
import (
"fmt"
"reflect"
)
// Reflective is a convenience wrapper for objects that makes it possible to
// extract property values from the object by property name
type Reflective struct{}
// StringValueForProperty returns a string value for the given property
// If the property doesn't exist, it returns an error
func (ref *Reflective) StringValueForProperty(propName string) (string, error) {
v := reflect.ValueOf(ref)
refVal := reflect.Indirect(v).FieldByName(propName)
if !refVal.IsValid() {
return "", fmt.Errorf("invalid property name: %s", propName)
}
strVal := fmt.Sprintf("%v", refVal)
return strVal, nil
}