Skip to content

Commit

Permalink
Allow int and floats when config values are fetched as float64 (#174)
Browse files Browse the repository at this point in the history
  • Loading branch information
madhuravi committed Jan 19, 2017
1 parent 88d0919 commit 5b3711d
Show file tree
Hide file tree
Showing 2 changed files with 31 additions and 3 deletions.
16 changes: 16 additions & 0 deletions config/config_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -206,6 +206,22 @@ func TestGetAsIntegerValue(t *testing.T) {
}
}

func TestGetAsFloatValue(t *testing.T) {
testCases := []struct {
value interface{}
}{
{float32(2)},
{float64(2)},
{int(2)},
{int32(2)},
{int64(2)},
}
for _, tc := range testCases {
cv := NewValue(NewStaticProvider(nil), "key", tc.value, true, Float, nil)
assert.Equal(t, float64(2), cv.AsFloat())
}
}

func TestNestedStructs(t *testing.T) {
provider := NewProviderGroup(
"test",
Expand Down
18 changes: 15 additions & 3 deletions config/value.go
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,8 @@ const (
Slice
// Dictionary contains words and their definitions
Dictionary
// Zero constants
_float64Zero = float64(0)
)

var _typeTimeDuration = reflect.TypeOf(time.Duration(0))
Expand Down Expand Up @@ -201,12 +203,22 @@ func (cv Value) TryAsBool() (bool, bool) {

// TryAsFloat attempts to return the configuration value as a float
func (cv Value) TryAsFloat() (float64, bool) {
f := float64(0)
v := cv.Value()
if val, err := convertValue(v, reflect.TypeOf(f)); v != nil && err == nil {
if val, err := convertValue(v, reflect.TypeOf(_float64Zero)); v != nil && err == nil {
return val.(float64), true
}
return f, false
switch val := v.(type) {
case int:
return float64(val), true
case int32:
return float64(val), true
case int64:
return float64(val), true
case float32:
return float64(val), true
default:
return _float64Zero, false
}
}

// AsString returns the configuration value as a string, or panics if not
Expand Down

0 comments on commit 5b3711d

Please sign in to comment.