envconf/datatype.go
2021-03-23 14:37:00 +01:00

85 lines
1.9 KiB
Go

package envconf
import ("fmt"
"errors"
"time"
"strconv")
type DataType int
const (
TypeNone DataType = iota
TypeInt DataType = iota
TypeDuration DataType = iota
TypeString DataType = iota
TypeBool DataType = iota
)
func (dtype DataType) String()(string) {
types := make(map[DataType]string)
types[TypeNone] = "none"
types[TypeInt] = "int"
types[TypeDuration] = "duration"
types[TypeString] = "string"
types[TypeBool] = "bool"
str, ok := types[dtype]
if ok {
return str
}
return "invalid"
}
type cValue struct {
intval int64
durval time.Duration
boolval bool
strval string
err error
}
func (dtype DataType) parse(key string, str string)(ret cValue) {
parsers := make(map[DataType](func(string,string)(cValue)))
parsers[TypeInt] = parseInt
parsers[TypeDuration] = parseDuration
parsers[TypeString] = parseString
parsers[TypeBool] = parseBool
parser, ok := parsers[dtype]
if ok {
return parser(key, str)
}
return
}
func parseInt(key string, str string)(ret cValue) {
val, err := strconv.ParseInt(str, 10, 64)
if err == nil {
ret.intval = val
} else {
ret.err = errors.New(fmt.Sprintf(`Environment variable "%s" is not of type int.`, key))
}
return
}
func parseDuration(key string, str string)(ret cValue) {
val, err := time.ParseDuration(str)
if err == nil {
ret.durval = val
} else {
ret.err = errors.New(fmt.Sprintf(`Environment variable "%s" is not of type duration.`, key))
}
return
}
func parseBool(key string, str string)(ret cValue) {
val, err := strconv.ParseBool(str)
if err == nil {
ret.boolval = val
} else {
ret.err = errors.New(fmt.Sprintf(`Environment variable "%s" is not of type bool.`, key))
}
return
}
func parseString(_ string, str string)(ret cValue) {
ret.strval = str
return
}