cfger/types.go

97 lines
2.1 KiB
Go

package cfger
import (
"fmt"
"os"
"strconv"
)
type OptionalItem struct {
key string
item any
found bool
}
// Required raises a fatal error if the item is not present
func (x OptionalItem) Required() OptionalItem {
if !x.found {
FatalErrorHandler(fmt.Errorf("required key %s not found in config", x.key))
os.Exit(1)
}
return x
}
// WithDefault returns the value if it is present, otherwise it returns the provided default value.
func (x OptionalItem) WithDefault(val any) OptionalItem {
if !x.found {
x.item = val
x.found = true
}
return x
}
// AsInt returns the value of x as an integer, or 0 if no value is present.
func (x OptionalItem) AsInt() int {
if !x.found {
return 0
}
return x.item.(int)
}
// ToInt parses x as an integer from a string and returns its value. If no value is present, 0 is returned, and if x is
// unparseable, a fatal error is raised.
func (x OptionalItem) ToInt() int {
if !x.found {
return 0
}
v, ok := x.item.(string)
if !ok {
FatalErrorHandler(fmt.Errorf("cfger: expected %s to be a string, got %T", x.key, x.item))
os.Exit(1)
}
iv, err := strconv.Atoi(v)
if err != nil {
FatalErrorHandler(fmt.Errorf("cfger: unable to parse %s as an integer: %w", x.key, err))
}
return iv
}
// AsString returns the value of x as a string, or an empty string if no value is present.
func (x OptionalItem) AsString() string {
if !x.found {
return ""
}
return x.item.(string)
}
// AsBool returns the value of x as a boolean, or an empty string if no value is present.
func (x OptionalItem) AsBool() bool {
if !x.found {
return false
}
return x.item.(bool)
}
// ToBool parses x as a boolean from a string and returns its value. If no value is present, false is returned, and if x
// is unparseable, a fatal error is raised.
func (x OptionalItem) ToBool() bool {
if !x.found {
return false
}
v, ok := x.item.(string)
if !ok {
FatalErrorHandler(fmt.Errorf("cfger: expected %s to be a string, got %T", x.key, x.item))
os.Exit(1)
}
iv, err := strconv.ParseBool(v)
if err != nil {
FatalErrorHandler(fmt.Errorf("cfger: unable to parse %s as an boolean: %w", x.key, err))
}
return iv
}