Skip to content

Commit

Permalink
Adding support for unsigned integers
Browse files Browse the repository at this point in the history
  • Loading branch information
juananrey committed Jan 29, 2020
1 parent e58101a commit fd086f1
Show file tree
Hide file tree
Showing 2 changed files with 41 additions and 1 deletion.
5 changes: 4 additions & 1 deletion init.go
Original file line number Diff line number Diff line change
Expand Up @@ -189,6 +189,8 @@ func (in initializer) initMetricFunc(field reflect.Value, structField reflect.St
labels[label.name] = value.String()
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
labels[label.name] = strconv.FormatInt(value.Int(), 10)
case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
labels[label.name] = strconv.FormatUint(value.Uint(), 10)
default:
// Should not happen since we've already checked this in the findLabelIndexes function
panic(fmt.Errorf("field %s has unsupported kind %v", label.name, label.kind))
Expand Down Expand Up @@ -231,7 +233,8 @@ func findLabelIndexes(typ reflect.Type, indexes map[label][]int, current ...int)
}

switch k := f.Type.Kind(); k {
case reflect.String, reflect.Bool, reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
case reflect.String, reflect.Bool, reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64,
reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
default:
return fmt.Errorf("field %s has unsupported type %v", labelTag, k)
}
Expand Down
37 changes: 37 additions & 0 deletions metrics_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -179,6 +179,43 @@ func Test_LabelsWithInts(t *testing.T) {
}, reportedLabels)
}

func Test_LabelsWithUints(t *testing.T) {
type labelsWithUints struct {
StringValue string `label:"string_value"`
UintValue uint `label:"uint_value"`
UintValue8 uint8 `label:"uint8_value"`
UintValue16 uint16 `label:"uint16_value"`
UintValue32 uint32 `label:"uint32_value"`
UintValue64 uint64 `label:"uint64_value"`
}

var metrics struct {
WithLabels func(labelsWithUints) prometheus.Histogram `name:"with_uints" help:"Parse uints as strings" buckets:""`
}

gotoprom.MustInit(&metrics, "testuints")

metrics.WithLabels(labelsWithUints{
StringValue: "string",
UintValue: 10,
UintValue8: 20,
UintValue16: 30,
UintValue32: 40,
UintValue64: 50,
}).Observe(288.0)

reportedLabels := retrieveReportedLabels(t, "testuints_with_uints")

assert.Equal(t, map[string]string{
"string_value": "string",
"uint_value": "10",
"uint8_value": "20",
"uint16_value": "30",
"uint32_value": "40",
"uint64_value": "50",
}, reportedLabels)
}

func Test_DefaultLabelValues(t *testing.T) {
type labelsWithEmptyValues struct {
StringWithEmpty string `label:"string_with_default" default:"none"`
Expand Down

0 comments on commit fd086f1

Please sign in to comment.