[cli] Add utility method to init float64 args

This commit is contained in:
Cyrille Nofficial 2019-12-27 15:22:43 +01:00
parent 33511a015a
commit e35d6f1381
2 changed files with 60 additions and 0 deletions

View File

@ -33,6 +33,21 @@ func SetIntDefaultValueFromEnv(value *int, key string, defaultValue int) error {
} }
return nil return nil
} }
func SetFloat64DefaultValueFromEnv(value *float64, key string, defaultValue float64) error {
var sVal string
if os.Getenv(key) != "" {
sVal = os.Getenv(key)
val, err := strconv.ParseFloat(sVal, 64)
if err != nil {
log.Printf("unable to convert string to float: %v", err)
return err
}
*value = val
} else {
*value = defaultValue
}
return nil
}
type Part interface { type Part interface {
Start() error Start() error
@ -71,6 +86,15 @@ func InitIntFlag(key string, defValue int) int {
return value return value
} }
func InitFloat64Flag(key string, defValue float64) float64 {
var value float64
err := SetFloat64DefaultValueFromEnv(&value, key, defValue)
if err != nil {
log.Panicf("invalid value: %v", err)
}
return value
}
func Connect(uri, username, password, clientId string) (MQTT.Client, error) { func Connect(uri, username, password, clientId string) (MQTT.Client, error) {
//create a ClientOptions struct setting the broker address, clientid, turn //create a ClientOptions struct setting the broker address, clientid, turn
//off trace output and set the default message handler //off trace output and set the default message handler

View File

@ -62,3 +62,39 @@ func TestSetIntDefaultValueFromEnv(t *testing.T) {
} }
} }
} }
func TestSetFloat64DefaultValueFromEnv(t *testing.T) {
err := os.Setenv("KEY1", "12.2")
err = os.Setenv("KEY2", "12")
err = os.Setenv("BAD_VALUE", "bad value")
if err != nil {
t.Errorf("unable to set env value: %v", err)
}
cases := []struct {
key string
defValue float64
expected float64
withError bool
}{
{"MISSING_KEY", 3.3, 3.3, false},
{"KEY1", 5, 12.2, false},
{"KEY2", 5, 12., false},
{"BAD_VALUE", 5, 0, true},
}
for _, c := range cases {
var value = 0.
err := SetFloat64DefaultValueFromEnv(&value, c.key, c.defValue)
if err != nil {
if !c.withError {
t.Errorf("SetFloat64DefaultValueFromEnv(*value, %v, %v): %v", c.key, c.defValue, err)
}
}
if c.withError && err == nil {
t.Errorf("SetFloat64DefaultValueFromEnv(*value, %v, %v): %v, wants an error", c.key, c.defValue, value)
} else if c.expected != value {
t.Errorf("SetFloat64DefaultValueFromEnv(*value, %v, %v): %v, wants %v", c.key, c.defValue, value, c.expected)
}
}
}