-
Notifications
You must be signed in to change notification settings - Fork 1
/
convert.go
124 lines (116 loc) · 2.19 KB
/
convert.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
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
package commonservice
import (
"fmt"
"strconv"
"time"
)
const (
layout = "02.01.2006"
)
// ToTimePtr converts an 'any' value as a Time pointer. Error is not possible, defaults to nil
func ToTimePtr(value any) *time.Time {
if value == nil {
return nil
}
switch v := value.(type) {
case time.Time:
return &v
case *time.Time:
return v
case string:
var t, _ = time.Parse(layout, v)
return &t
case *string:
var t, _ = time.Parse(layout, *v)
return &t
}
return nil
}
// ToStringPtr converts an 'any' value as a string pointer
func ToStringPtr(value any) *string {
if value == nil {
return nil
}
switch v := value.(type) {
case *string:
return v
}
var res = fmt.Sprintf("%v", value)
return &res
}
// ToInt converts an 'any' value as int and returns a default value in case of error
func ToInt(value any, defaultValue int) int {
switch v := value.(type) {
case int:
return v
case *int:
return *v
case int64:
return int(v)
case *int64:
return int(*v)
case int32:
return int(v)
case *int32:
return int(*v)
case float32:
return int(v)
case *float32:
return int(*v)
case float64:
return int(v)
case *float64:
return int(*v)
case string:
return atoi(v, defaultValue)
case *string:
return atoi(*v, defaultValue)
default:
return defaultValue
}
}
// ToFloat converts an 'any' value as float64 and returns a default value in case of error
func ToFloat(value any, defaultValue float64) float64 {
switch v := value.(type) {
case int:
return float64(v)
case *int:
return float64(*v)
case int64:
return float64(v)
case *int64:
return float64(*v)
case int32:
return float64(v)
case *int32:
return float64(*v)
case float32:
return float64(v)
case *float32:
return float64(*v)
case float64:
return v
case *float64:
return *v
case string:
return atof(v, defaultValue)
case *string:
return atof(*v, defaultValue)
default:
return defaultValue
}
}
func atoi(value string, defaultValue int) int {
var res, err = strconv.Atoi(value)
if err != nil {
return defaultValue
}
return res
}
func atof(value string, defaultValue float64) float64 {
var res, err = strconv.ParseFloat(value, 64)
if err != nil {
return defaultValue
}
return res
}