Merge pull request #132 from prometheus/fabxc/lname-json

Validate LabelName/LabelSet on JSON unmarshaling.
This commit is contained in:
Fabian Reinartz 2015-06-08 13:26:47 +02:00
commit f17ca6af6d
2 changed files with 33 additions and 0 deletions

View File

@ -14,6 +14,7 @@
package model
import (
"encoding/json"
"fmt"
"regexp"
"strings"
@ -81,6 +82,19 @@ func (ln *LabelName) UnmarshalYAML(unmarshal func(interface{}) error) error {
return nil
}
// UnmarshalJSON implements the json.Unmarshaler interface.
func (ln *LabelName) UnmarshalJSON(b []byte) error {
var s string
if err := json.Unmarshal(b, &s); err != nil {
return err
}
if !LabelNameRE.MatchString(s) {
return fmt.Errorf("%q is not a valid label name", s)
}
*ln = LabelName(s)
return nil
}
// LabelNames is a sortable LabelName slice. In implements sort.Interface.
type LabelNames []LabelName

View File

@ -14,6 +14,7 @@
package model
import (
"encoding/json"
"fmt"
"sort"
"strings"
@ -62,3 +63,21 @@ func (l LabelSet) MergeFromMetric(m Metric) {
l[k] = v
}
}
// UnmarshalJSON implements the json.Unmarshaler interface.
func (l *LabelSet) UnmarshalJSON(b []byte) error {
var m map[LabelName]LabelValue
if err := json.Unmarshal(b, &m); err != nil {
return err
}
// encoding/json only unmarshals maps of the form map[string]T. It treats
// LabelName as a string and does not call its UnmarshalJSON method.
// Thus, we have to replicate the behavior here.
for ln := range m {
if !LabelNameRE.MatchString(string(ln)) {
return fmt.Errorf("%q is not a valid label name", ln)
}
}
*l = LabelSet(m)
return nil
}