add metric

This commit is contained in:
Roy Olav Purser 2021-03-25 12:06:08 +01:00
parent 108cd021d1
commit 8d48099517
No known key found for this signature in database
GPG Key ID: 0BA77797F072BC52
4 changed files with 42 additions and 0 deletions

View File

@ -5,6 +5,7 @@ type DataType int
const (
TypeNone DataType = iota
TypeInt DataType = iota
TypeMetric DataType = iota
TypeDuration DataType = iota
TypeString DataType = iota
TypeDirectory DataType = iota

View File

@ -114,6 +114,16 @@ func (c *Config) GetInt(key string)(int64) {
}
return 0
}
func (c *Config) GetMetric(key string)(int64) {
if c.parsed {
upper := strings.ToUpper(key)
entry, ok := c.env[upper]
if ok {
return entry.parsed.intval
}
}
return 0
}
func (c *Config) GetDirectory(key string)(string) {
if c.parsed {
upper := strings.ToUpper(key)

View File

@ -1,5 +1,6 @@
package envconf
import ("strconv"
"strings"
"fmt"
"errors"
"os"
@ -16,6 +17,31 @@ func parseInt(key string, str string)(ret cValue) {
return
}
func parseMetric(key string, str string)(ret cValue) {
mod := int64(1)
str = strings.ToUpper(str)
if strings.HasSuffix(str, "K") {
mod = 1024
str = strings.TrimSuffix(str, "K")
} else if strings.HasSuffix(str, "M") {
mod = 1024 * 1024
str = strings.TrimSuffix(str, "M")
} else if strings.HasSuffix(str, "G") {
mod = 1024 * 1024 * 1024
str = strings.TrimSuffix(str, "G")
} else if strings.HasSuffix(str, "T") {
mod = 1024 * 1024 * 1024 * 1024
str = strings.TrimSuffix(str, "T")
}
val, err := strconv.ParseInt(str, 10, 64)
if err == nil {
ret.intval = mod * 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 {
@ -50,6 +76,7 @@ func parseDirectory(_ string, str string)(ret cValue) {
return
}
func parseString(_ string, str string)(ret cValue) {
ret.strval = str
return

View File

@ -7,24 +7,28 @@ var tInfo map[DataType]dataTypeInfo
func init() {
tInfo = make(map[DataType]dataTypeInfo)
var intInfo dataTypeInfo
var metricInfo dataTypeInfo
var durInfo dataTypeInfo
var strInfo dataTypeInfo
var dirInfo dataTypeInfo
var boolInfo dataTypeInfo
intInfo.name = "int"
metricInfo.name = "metric"
durInfo.name = "duration"
dirInfo.name = "directory"
strInfo.name = "string"
boolInfo.name = "bool"
intInfo.parser = parseInt
metricInfo.parser = parseMetric
durInfo.parser = parseDuration
dirInfo.parser = parseDirectory
strInfo.parser = parseString
boolInfo.parser = parseBool
tInfo[TypeInt] = intInfo
tInfo[TypeMetric] = metricInfo
tInfo[TypeDuration] = durInfo
tInfo[TypeString] = strInfo
tInfo[TypeDirectory] = dirInfo