Skip to content

Commit

Permalink
add monkit:ignore tag for structs
Browse files Browse the repository at this point in the history
  • Loading branch information
zeebo committed Dec 5, 2024
1 parent 8eee163 commit 42ff3a3
Show file tree
Hide file tree
Showing 2 changed files with 57 additions and 1 deletion.
13 changes: 12 additions & 1 deletion struct.go
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,10 @@

package monkit

import "reflect"
import (
"reflect"
"strings"
)

var (
f64Type = reflect.TypeOf(float64(0))
Expand All @@ -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) {
Expand Down
45 changes: 45 additions & 0 deletions struct_test.go
Original file line number Diff line number Diff line change
@@ -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)
}
}

0 comments on commit 42ff3a3

Please sign in to comment.