-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathstringify.go
42 lines (39 loc) · 898 Bytes
/
stringify.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
package syncbox
import (
"fmt"
"reflect"
)
// ToString receives a pointer of structure and stringify it
func ToString(a interface{}) string {
str := ""
structType := reflect.TypeOf(a).Elem()
structVal := reflect.ValueOf(a).Elem()
for i := 0; i < structVal.NumField(); i++ {
fieldType := structType.Field(i)
fieldVal := structVal.Field(i)
fieldName := fieldType.Name
str += fieldName + ": "
switch fieldVal.Kind() {
case reflect.Slice:
str += getSliceAndArrayString(fieldVal)
case reflect.Array:
str += getSliceAndArrayString(fieldVal)
default:
str += fmt.Sprintf("%v", fieldVal)
}
str += "\n"
}
return str
}
func getSliceAndArrayString(field reflect.Value) string {
str := ""
if field.Len() > 0 {
switch field.Type() {
case reflect.TypeOf([]byte(nil)):
str += string(field.Bytes())
default:
str += fmt.Sprintf("%v", field)
}
}
return str
}