From 42ff3a3543daa6a24131fe233fc3f32a4331b2ee Mon Sep 17 00:00:00 2001 From: Jeff Wendling Date: Thu, 5 Dec 2024 08:48:56 -0500 Subject: [PATCH] add monkit:ignore tag for structs --- struct.go | 13 ++++++++++++- struct_test.go | 45 +++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 57 insertions(+), 1 deletion(-) create mode 100644 struct_test.go diff --git a/struct.go b/struct.go index ea184c0..241b715 100644 --- a/struct.go +++ b/struct.go @@ -14,7 +14,10 @@ package monkit -import "reflect" +import ( + "reflect" + "strings" +) var ( f64Type = reflect.TypeOf(float64(0)) @@ -36,10 +39,18 @@ func StatSourceFromStruct(key SeriesKey, structData interface{}) StatSource { } return StatSourceFunc(func(cb func(key SeriesKey, field string, val float64)) { + nextField: for i := 0; i < typ.NumField(); i++ { field := deref(val.Field(i)) field_type := field.Type() + parts := strings.Split(typ.Field(i).Tag.Get("monkit"), ",") + for _, part := range parts { + if part == "ignore" { + continue nextField + } + } + if field_type.Kind() == reflect.Struct && field.CanInterface() { child_source := StatSourceFromStruct(key, field.Interface()) child_source.Stats(func(key SeriesKey, field string, val float64) { diff --git a/struct_test.go b/struct_test.go new file mode 100644 index 0000000..2139eb7 --- /dev/null +++ b/struct_test.go @@ -0,0 +1,45 @@ +package monkit + +import ( + "reflect" + "testing" +) + +func TestStatSourceFromStruct(t *testing.T) { + type SubStruct struct { + SubBool bool + SubFloat float64 + SubInt int64 + Ignored float64 `monkit:"ignore"` + } + + result := Collect(StatSourceFromStruct(NewSeriesKey("struct"), + struct { + SomeBool bool + SomeFloat float64 + SomeInt int64 + Ignored float64 `monkit:"ignore"` + Sub SubStruct + Skip struct { + Nope int64 + } `monkit:"whatever,ignore"` + }{ + SomeInt: 5, + SomeBool: true, + Sub: SubStruct{ + SubFloat: 3.2, + }, + }, + )) + + if !reflect.DeepEqual(result, map[string]float64{ + "struct SomeBool": 1, + "struct SomeFloat": 0, + "struct SomeInt": 5, + "struct Sub.SubBool": 0, + "struct Sub.SubFloat": 3.2, + "struct Sub.SubInt": 0, + }) { + t.Fatal("unexpected result", result) + } +}