/
if.go
101 lines (93 loc) · 1.63 KB
/
if.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
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
package goutils
import (
"fmt"
"strconv"
)
type ifThen struct {
c bool
t interface{}
e interface{}
v interface{}
}
func (i *ifThen) If(c bool) *ifThen {
i.c = c
return i
}
func (i *ifThen) Then(v interface{}) *ifThen {
i.t = v
return i
}
func (i *ifThen) Else(v interface{}) *ifThen {
i.e = v
return i
}
func (i *ifThen) String() string {
if i.c {
i.v = i.t
} else {
i.v = i.e
}
return fmt.Sprintf("%v", i.v)
}
func (i *ifThen) Int() (int64, error) {
if i.c {
i.v = i.t
} else {
i.v = i.e
}
switch i.v.(type) {
case int64:
return i.v.(int64), nil
case int32:
return int64(i.v.(int32)), nil
case int:
return int64(i.v.(int)), nil
case int8:
return int64(i.v.(int8)), nil
case int16:
return int64(i.v.(int16)), nil
case float32:
return int64(i.v.(float32)), nil
case float64:
return int64(i.v.(float64)), nil
case []byte:
i, err := strconv.ParseInt(string(i.v.([]byte)), 10, 64)
if err != nil {
return 0, err
}
return i, nil
case string:
i, err := strconv.ParseInt(i.v.(string), 10, 64)
if err != nil {
return 0, err
}
return i, nil
}
return 0, fmt.Errorf("Unsupported type: %v", i.v)
}
func (i *ifThen) Float() (float64, error) {
if i.c {
i.v = i.t
} else {
i.v = i.e
}
switch i.v.(type) {
case float32:
return float64(i.v.(float32)), nil
case float64:
return i.v.(float64), nil
case string:
i, err := strconv.ParseFloat(i.v.(string), 64)
if err != nil {
return 0, err
}
return i, nil
case []byte:
i, err := strconv.ParseFloat(string(i.v.([]byte)), 64)
if err != nil {
return 0, err
}
return i, nil
}
return 0, fmt.Errorf("Unsupported type: %v", i.v)
}