[#493] node/config: Implement string caster
Signed-off-by: Leonard Lyubich <leonard@nspcc.ru>
This commit is contained in:
parent
7e11bf9a55
commit
cbe3e0a271
4 changed files with 45 additions and 1 deletions
|
@ -28,3 +28,22 @@ func StringSlice(c *Config, name string) []string {
|
|||
func StringSliceSafe(c *Config, name string) []string {
|
||||
return cast.ToStringSlice(c.Value(name))
|
||||
}
|
||||
|
||||
// String reads configuration value
|
||||
// from c by name and casts it to string.
|
||||
//
|
||||
// Panics if value can not be casted.
|
||||
func String(c *Config, name string) string {
|
||||
x, err := cast.ToStringE(c.Value(name))
|
||||
panicOnErr(err)
|
||||
|
||||
return x
|
||||
}
|
||||
|
||||
// StringSafe reads configuration value
|
||||
// from c by name and casts it to string.
|
||||
//
|
||||
// Returns "" if value can not be casted.
|
||||
func StringSafe(c *Config, name string) string {
|
||||
return cast.ToString(c.Value(name))
|
||||
}
|
||||
|
|
|
@ -28,3 +28,19 @@ func TestStringSlice(t *testing.T) {
|
|||
require.Nil(t, val)
|
||||
})
|
||||
}
|
||||
|
||||
func TestString(t *testing.T) {
|
||||
forEachFileType("test/config", func(c *config.Config) {
|
||||
c = c.Sub("string")
|
||||
|
||||
val := config.String(c, "correct")
|
||||
require.Equal(t, "some string", val)
|
||||
|
||||
require.Panics(t, func() {
|
||||
config.String(c, "incorrect")
|
||||
})
|
||||
|
||||
val = config.StringSafe(c, "incorrect")
|
||||
require.Empty(t, val)
|
||||
})
|
||||
}
|
||||
|
|
|
@ -10,5 +10,9 @@
|
|||
"string2"
|
||||
],
|
||||
"incorrect": null
|
||||
},
|
||||
"string": {
|
||||
"correct": "some string",
|
||||
"incorrect": []
|
||||
}
|
||||
}
|
||||
|
|
|
@ -10,4 +10,9 @@ string_slice:
|
|||
- string1
|
||||
- string2
|
||||
|
||||
incorrect:
|
||||
incorrect:
|
||||
|
||||
string:
|
||||
correct: some string
|
||||
|
||||
incorrect: []
|
||||
|
|
Loading…
Reference in a new issue