-
Notifications
You must be signed in to change notification settings - Fork 0
/
parser.go
45 lines (37 loc) · 1.12 KB
/
parser.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
package envloader
import (
"fmt"
"reflect"
)
type stringParser struct {
parserMap parserMap
}
func newStringParser() *stringParser {
return &stringParser{
parserMap: createParserMap(),
}
}
func (c *stringParser) Parse(target string, targetType reflect.Kind) (interface{}, error) {
parser, found := c.parserMap[targetType]
if !found {
return nil, fmt.Errorf("unsupported type %v", targetType)
}
return parser(target)
}
type parserMethod func(val string) (interface{}, error)
type parserMap map[reflect.Kind]parserMethod
func createParserMap() parserMap {
parsers := parsers{}
parserMap := make(map[reflect.Kind]parserMethod)
parserMap[reflect.Interface] = parsers.ParseInterface
parserMap[reflect.String] = parsers.ParseString
parserMap[reflect.Int] = parsers.ParseInt
parserMap[reflect.Int8] = parsers.ParseInt8
parserMap[reflect.Int16] = parsers.ParseInt16
parserMap[reflect.Int32] = parsers.ParseInt32
parserMap[reflect.Int64] = parsers.ParseInt64
parserMap[reflect.Float32] = parsers.ParseFloat32
parserMap[reflect.Float64] = parsers.ParseFloat64
parserMap[reflect.Bool] = parsers.ParseBool
return parserMap
}