-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathutils.go
94 lines (85 loc) · 2.27 KB
/
utils.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
package main
import (
"fmt"
"reflect"
"strings"
)
const (
b = uint64(1)
kb = 1024 * b
mb = 1024 * kb
gb = 1024 * mb
)
func formatBytes(bytes uint64) string {
switch {
case bytes < kb:
return fmt.Sprintf("%dB", bytes)
case bytes < mb:
return fmt.Sprintf("%.2fKB", float64(bytes)/float64(kb))
case bytes < gb:
return fmt.Sprintf("%.2fMB", float64(bytes)/float64(mb))
default:
return fmt.Sprintf("%.2fGB", float64(bytes)/float64(gb))
}
}
func convertToBoolean(val interface{}) bool {
switch v := val.(type) {
case string:
// Handle string type
// Convert string to boolean, e.g., "true" or "1" -> true
return strings.ToLower(v) == "true" || v == "1"
case bool:
// Handle boolean type
// No conversion needed, already a boolean
return v
case int:
// Handle int type
// Convert int to boolean, e.g., 0 -> false, any other value -> true
return v != 0
}
// Type not supported
return false
}
// copy data to data2,and convert the fields
// data and data2 should have the similar struct
func convertToFormattedString(data interface{}, data2 interface{}) {
v := reflect.ValueOf(data)
if v.Kind() == reflect.Ptr {
v = v.Elem()
}
v2 := reflect.ValueOf(data2)
if v2.Kind() == reflect.Ptr {
v2 = v2.Elem()
}
for i := 0; i < v.NumField(); i++ {
field := v.Field(i)
field2 := v2.Field(i)
switch field.Kind() {
case reflect.Ptr:
if field.IsNil() {
continue
}
elem := field.Elem()
// elem2 := field2.Elem()
if elem.Kind() == reflect.Struct {
field2.Set(reflect.New(field2.Type().Elem()))
elem2 := field2.Elem()
convertToFormattedString(elem.Addr().Interface(), elem2.Addr().Interface())
}
case reflect.Slice:
sliceType := reflect.SliceOf(field2.Type().Elem())
newSlice := reflect.MakeSlice(sliceType, field.Len(), field.Len())
field2.Set(newSlice)
for j := 0; j < field.Len(); j++ {
convertToFormattedString(field.Index(j).Addr().Interface(), field2.Index(j).Addr().Interface())
}
case reflect.Uint64, reflect.Int:
str := formatBytes(field.Uint())
field2.SetString(str)
case reflect.Struct:
convertToFormattedString(field.Addr().Interface(), field2.Addr().Interface())
default:
field2.Set(field)
}
}
}