-
Notifications
You must be signed in to change notification settings - Fork 43
/
strconv.go
98 lines (88 loc) · 1.94 KB
/
strconv.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
package codec
import (
"encoding/json"
"fmt"
"strconv"
)
func Atoi(i string) int {
raw, _ := strconv.Atoi(i)
return raw
}
func Itoa(i int) string {
return fmt.Sprint(i)
}
func Atof(i string) float64 {
raw, _ := strconv.ParseFloat(i, 64)
return raw
}
func Atob(i string) bool {
raw, _ := strconv.ParseBool(i)
return raw
}
func AnyToBytes(i interface{}) (result []byte) {
var b []byte
defer func() {
if err := recover(); err != nil {
result = []byte(fmt.Sprintf("%v", i))
}
}()
if i == nil {
return []byte{}
}
switch s := i.(type) {
case nil:
return []byte{}
case string:
b = []byte(s)
case []byte:
b = s[0:]
case bool:
b = []byte(strconv.FormatBool(s))
case float64:
return []byte(strconv.FormatFloat(s, 'f', -1, 64))
case float32:
return []byte(strconv.FormatFloat(float64(s), 'f', -1, 32))
case int:
return []byte(strconv.Itoa(s))
case int64:
return []byte(strconv.FormatInt(s, 10))
case int32:
return []byte(strconv.Itoa(int(s)))
case int16:
return []byte(strconv.FormatInt(int64(s), 10))
case int8:
return []byte(strconv.FormatInt(int64(s), 10))
case uint:
return []byte(strconv.FormatUint(uint64(s), 10))
case uint64:
return []byte(strconv.FormatUint(s, 10))
case uint32:
return []byte(strconv.FormatUint(uint64(s), 10))
case uint16:
return []byte(strconv.FormatUint(uint64(s), 10))
case uint8:
return []byte(strconv.FormatUint(uint64(s), 10))
case fmt.Stringer:
return []byte(s.String())
case error:
return []byte(s.Error())
//case io.Reader:
// if ret != nil && ret.Read != nil {
// bytes, _ = ioutil.ReadAll(ret)
// return bytes
// }
// return []byte(fmt.Sprintf("%v", i))
default:
// 尝试将i作为map转换成JSON
if jsonBytes, err := json.Marshal(i); err == nil {
b = jsonBytes
} else {
// 如果转换失败,则回退到使用fmt.Sprintf
b = []byte(fmt.Sprintf("%v", i))
}
}
return b
}
func AnyToString(i interface{}) string {
return string(AnyToBytes(i))
}