]> git repos ~mattia - go-utility.git/commitdiff
Reflect Field with Tags v0.0.3
authorMattia Cabrini <dev@matiacabrini.com>
Sat, 8 Jul 2023 07:54:59 +0000 (09:54 +0200)
committerMattia Cabrini <dev@matiacabrini.com>
Sat, 8 Jul 2023 07:54:59 +0000 (09:54 +0200)
reflect.go
reflect_test.go

index 1589c0c190320b3304d5b168a04753a3ca5d7ce8..82300faa9e86a4d6a727d9f2980f88691e6aa3a7 100644 (file)
@@ -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()
        }
 
index cc27ac2b75f58daf013796c2c979cf320b617443..f95f6af6a554eb28234de10abacbcf07a04c90ab 100644 (file)
@@ -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}