Skip to content

Commit 274ab3a

Browse files
committed
Allow empty namespace, namespace chain for nested structs
1 parent 12d8def commit 274ab3a

File tree

2 files changed

+14
-18
lines changed

2 files changed

+14
-18
lines changed

init.go

+14-4
Original file line numberDiff line numberDiff line change
@@ -82,7 +82,13 @@ func (in initializer) Init(metrics interface{}, namespace string) error {
8282
return fmt.Errorf("expected pointer to metrics struct, got %q", metricsPtr.Kind())
8383
}
8484

85-
return in.initMetrics(metricsPtr.Elem(), namespace)
85+
var namespaces []string
86+
87+
if namespace != "" {
88+
namespaces = append(namespaces, namespace)
89+
}
90+
91+
return in.initMetrics(metricsPtr.Elem(), namespaces...)
8692
}
8793

8894
func (in initializer) initMetrics(group reflect.Value, namespaces ...string) error {
@@ -100,8 +106,12 @@ func (in initializer) initMetrics(group reflect.Value, namespaces ...string) err
100106
}
101107
} else if fieldType.Type.Kind() == reflect.Struct {
102108
namespace, ok := fieldType.Tag.Lookup("namespace")
103-
if !ok {
104-
return fmt.Errorf("field %s does not have the namespace tag defined", fieldType.Name)
109+
if !ok || namespace == "" {
110+
if err := in.initMetrics(field, namespaces...); err != nil {
111+
return err
112+
}
113+
114+
continue
105115
}
106116
if err := in.initMetrics(field, append(namespaces, namespace)...); err != nil {
107117
return err
@@ -134,7 +144,7 @@ func (in initializer) initMetricFunc(field reflect.Value, structField reflect.St
134144
// Validate the input of the metric function, it should have zero or one arguments
135145
// If it has one argument, it should be a struct correctly tagged with label names
136146
// If there are no input arguments, this metric will not have labels registered
137-
var labelIndexes = make(map[label][]int)
147+
labelIndexes := make(map[label][]int)
138148
if fieldType.NumIn() > 1 {
139149
return fmt.Errorf("field %s: expected 1 in arg, got %d", structField.Name, fieldType.NumIn())
140150
} else if fieldType.NumIn() == 1 {

init_test.go

-14
Original file line numberDiff line numberDiff line change
@@ -86,20 +86,6 @@ func TestInitializer_Init(t *testing.T) {
8686
Something string
8787
}{},
8888
},
89-
{
90-
desc: "sub-struct doesn't define its namespace",
91-
metrics: &struct {
92-
Inner struct{}
93-
}{},
94-
},
95-
{
96-
desc: "sub-struct can't be initialized",
97-
metrics: &struct {
98-
Inner struct {
99-
Deeper struct{} `thisdoesnothaveanamespace:"nothing"`
100-
} `namespace:"thishasanamespace"`
101-
}{},
102-
},
10389
{
10490
desc: "non-exported field",
10591
metrics: &struct {

0 commit comments

Comments
 (0)