-
Notifications
You must be signed in to change notification settings - Fork 33
/
struct.go
79 lines (67 loc) · 2.24 KB
/
struct.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
// Copyright (C) 2015 Space Monkey, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package monkit
import (
"reflect"
"strings"
)
var (
f64Type = reflect.TypeOf(float64(0))
boolType = reflect.TypeOf(bool(false))
)
type emptyStatSource struct{}
func (emptyStatSource) Stats(cb func(key SeriesKey, field string, val float64)) {}
// StatSourceFromStruct uses the reflect package to implement the Stats call
// across all float64-castable and bool-castable fields of the struct.
func StatSourceFromStruct(key SeriesKey, structData interface{}) StatSource {
val := deref(reflect.ValueOf(structData))
typ := val.Type()
if typ.Kind() != reflect.Struct {
return emptyStatSource{}
}
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) {
cb(key, typ.Field(i).Name+"."+field, val)
})
} else if field_type.ConvertibleTo(f64Type) {
cb(key, typ.Field(i).Name, field.Convert(f64Type).Float())
} else if field_type.ConvertibleTo(boolType) {
if field.Convert(boolType).Bool() {
cb(key, typ.Field(i).Name, 1)
} else {
cb(key, typ.Field(i).Name, 0)
}
}
}
})
}
// if val is a pointer, deref until it isn't
func deref(val reflect.Value) reflect.Value {
for val.Type().Kind() == reflect.Ptr {
val = val.Elem()
}
return val
}