Skip to content
This repository has been archived by the owner on Oct 17, 2018. It is now read-only.

Commit

Permalink
Extract NewType function to be reused
Browse files Browse the repository at this point in the history
  • Loading branch information
Chao Wang committed Nov 19, 2017
1 parent 1cb339d commit 190fd2e
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 10 deletions.
29 changes: 20 additions & 9 deletions metric/types.go
Original file line number Diff line number Diff line change
Expand Up @@ -56,20 +56,31 @@ func (t Type) String() string {
}
}

// NewType creates a metric type from a type string.
func NewType(typeStr string) (Type, error) {
validTypeStrs := make([]string, 0, len(validTypes))
for _, valid := range validTypes {
if typeStr == valid.String() {
return valid, nil
}
validTypeStrs = append(validTypeStrs, valid.String())
}
return UnknownType, fmt.Errorf("invalid metric type '%s', valid types are: %s",
typeStr, strings.Join(validTypeStrs, ", "))
}

// UnmarshalYAML unmarshals YAML object into a metric type.
func (t *Type) UnmarshalYAML(unmarshal func(interface{}) error) error {
var str string
if err := unmarshal(&str); err != nil {
return err
}
validTypeStrs := make([]string, 0, len(validTypes))
for _, valid := range validTypes {
if str == valid.String() {
*t = valid
return nil
}
validTypeStrs = append(validTypeStrs, valid.String())

mt, err := NewType(str)
if err != nil {
return err
}
return fmt.Errorf("invalid metric type '%s' valid types are: %s",
str, strings.Join(validTypeStrs, ", "))

*t = mt
return nil
}
2 changes: 1 addition & 1 deletion metric/types_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,6 @@ func TestTypeUnmarshalYAMLErrors(t *testing.T) {
var typ Type
err := yaml.Unmarshal([]byte(input), &typ)
require.Error(t, err)
require.Equal(t, "invalid metric type '"+input+"' valid types are: counter, timer, gauge", err.Error())
require.Equal(t, "invalid metric type '"+input+"', valid types are: counter, timer, gauge", err.Error())
}
}

0 comments on commit 190fd2e

Please sign in to comment.