From 699890e21635d3e2bb0f4bae0f4ef2bccf85b787 Mon Sep 17 00:00:00 2001 From: Mattia Cabrini Date: Sat, 8 Jul 2023 09:54:59 +0200 Subject: [PATCH] Reflect Field with Tags --- reflect.go | 12 ++++++++++-- reflect_test.go | 20 ++++++++++++++++++-- 2 files changed, 28 insertions(+), 4 deletions(-) diff --git a/reflect.go b/reflect.go index 1589c0c..82300fa 100644 --- a/reflect.go +++ b/reflect.go @@ -88,14 +88,22 @@ func GetMethod(obj interface{}, name string, suffix string) GenericFunc { return nil } -func GetProperty(obj interface{}, name string, suffix string) interface{} { +func GetProperty(obj interface{}, name string, suffix string, tags ...string) interface{} { to := reflect.TypeOf(obj) vo := reflect.ValueOf(obj) - _, b := to.FieldByName(name + suffix) + fieldTO, b := to.FieldByName(name + suffix) + + for _, tx := range tags { + if tagValue := fieldTO.Tag.Get(tx); tagValue != "true" { + b = false + break + } + } if b { fieldVO := vo.FieldByName(name + suffix) + return fieldVO.Interface() } diff --git a/reflect_test.go b/reflect_test.go index cc27ac2..f95f6af 100644 --- a/reflect_test.go +++ b/reflect_test.go @@ -27,8 +27,8 @@ package utility import "testing" type testType struct { - A int - B int + A int `con:"true" con2:"true"` + B int `con:"true" con2:"false"` } func (t *testType) GetAB(a, b int) (int, int) { @@ -172,6 +172,22 @@ func TestFieldOk(t *testing.T) { } } +func TestFieldTag(t *testing.T) { + obj := testType{0, 1} + + i := GetProperty(obj, "B", "", "con", "con2") + + if i != nil { + t.Fail() + } + + i = GetProperty(obj, "A", "", "con", "con2") + + if i.(int) != 0 { + t.Fail() + } +} + func TestFieldKo(t *testing.T) { obj := testType{0, 1} -- 2.43.0