altsrc: Parse durations from strings
This commit is contained in:
parent
b2bf3c5abe
commit
01b6b9192c
@ -71,24 +71,28 @@ func (fsm *MapInputSource) Int(name string) (int, error) {
|
||||
func (fsm *MapInputSource) Duration(name string) (time.Duration, error) {
|
||||
otherGenericValue, exists := fsm.valueMap[name]
|
||||
if exists {
|
||||
otherValue, isType := otherGenericValue.(time.Duration)
|
||||
if !isType {
|
||||
return 0, incorrectTypeForFlagError(name, "duration", otherGenericValue)
|
||||
}
|
||||
return otherValue, nil
|
||||
return castDuration(name, otherGenericValue)
|
||||
}
|
||||
nestedGenericValue, exists := nestedVal(name, fsm.valueMap)
|
||||
if exists {
|
||||
otherValue, isType := nestedGenericValue.(time.Duration)
|
||||
if !isType {
|
||||
return 0, incorrectTypeForFlagError(name, "duration", nestedGenericValue)
|
||||
}
|
||||
return otherValue, nil
|
||||
return castDuration(name, nestedGenericValue)
|
||||
}
|
||||
|
||||
return 0, nil
|
||||
}
|
||||
|
||||
func castDuration(name string, value interface{}) (time.Duration, error) {
|
||||
if otherValue, isType := value.(time.Duration); isType {
|
||||
return otherValue, nil
|
||||
}
|
||||
otherStringValue, isType := value.(string)
|
||||
parsedValue, err := time.ParseDuration(otherStringValue)
|
||||
if !isType || err != nil {
|
||||
return 0, incorrectTypeForFlagError(name, "duration", value)
|
||||
}
|
||||
return parsedValue, nil
|
||||
}
|
||||
|
||||
// Float64 returns an float64 from the map if it exists otherwise returns 0
|
||||
func (fsm *MapInputSource) Float64(name string) (float64, error) {
|
||||
otherGenericValue, exists := fsm.valueMap[name]
|
||||
|
25
altsrc/map_input_source_test.go
Normal file
25
altsrc/map_input_source_test.go
Normal file
@ -0,0 +1,25 @@
|
||||
package altsrc
|
||||
|
||||
import (
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
func TestMapDuration(t *testing.T) {
|
||||
inputSource := &MapInputSource{
|
||||
file: "test",
|
||||
valueMap: map[interface{}]interface{}{
|
||||
"duration_of_duration_type": time.Minute,
|
||||
"duration_of_string_type": "1m",
|
||||
"duration_of_int_type": 1000,
|
||||
},
|
||||
}
|
||||
d, err := inputSource.Duration("duration_of_duration_type")
|
||||
expect(t, time.Minute, d)
|
||||
expect(t, nil, err)
|
||||
d, err = inputSource.Duration("duration_of_string_type")
|
||||
expect(t, time.Minute, d)
|
||||
expect(t, nil, err)
|
||||
d, err = inputSource.Duration("duration_of_int_type")
|
||||
refute(t, nil, err)
|
||||
}
|
Loading…
Reference in New Issue
Block a user