-
Notifications
You must be signed in to change notification settings - Fork 0
/
string_cast.go
executable file
·73 lines (66 loc) · 1.71 KB
/
string_cast.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
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
package goweb
import (
"errors"
"reflect"
"strconv"
"strings"
)
// StringCast cast string type value to dest type
// Supported dest types: bool, int(int8 ~ int64), uint(uint8 ~ uint64), string, []bool, []int(int8 ~ int64), []uint(uint8 ~ uint64), []string;
func StringCast(src string, typo *reflect.Type) (interface{}, error) {
var v interface{}
var err error
switch (*typo).Kind() {
case reflect.String:
v = src
case reflect.Bool:
v = src == "true"
case reflect.Int:
v, err = strconv.Atoi(src)
case reflect.Int8:
v, err = strconv.ParseInt(src, 10, 8)
case reflect.Int16:
v, err = strconv.ParseInt(src, 10, 16)
case reflect.Int32:
v, err = strconv.ParseInt(src, 10, 32)
case reflect.Int64:
v, err = strconv.ParseInt(src, 10, 64)
case reflect.Uint:
var vOfU64 uint64
if vOfU64, err = strconv.ParseUint(src, 10, 0); err == nil {
v = uint(vOfU64)
}
case reflect.Uint8:
v, err = strconv.ParseUint(src, 10, 8)
case reflect.Uint16:
v, err = strconv.ParseUint(src, 10, 16)
case reflect.Uint32:
v, err = strconv.ParseUint(src, 10, 32)
case reflect.Uint64:
v, err = strconv.ParseUint(src, 10, 64)
case reflect.Slice:
list := reflect.MakeSlice(*typo, 0, 0)
if src == "" {
return list.Interface(), err
}
parts := strings.Split(src, ",")
elementType := (*typo).Elem()
if elementType.Kind() == reflect.String {
return parts, nil
}
for _, itemV := range parts {
vCtv, err := StringCast(itemV, &elementType)
if err != nil {
return nil, err
}
list = reflect.AppendSlice(list, reflect.ValueOf(vCtv))
}
v = list.Interface()
default:
return nil, errors.New("Unsupported type cast: " + (*typo).Kind().String())
}
if err != nil {
return nil, err
}
return v, nil
}