/
message.go
80 lines (64 loc) · 1.57 KB
/
message.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
package echovr
import (
"fmt"
"reflect"
)
type Message interface {
Symbol() uint64
Stream(s *EasyStream) error
}
type Serializable interface {
Stream(s *EasyStream) error
}
func Deserialize(obj Serializable, b []byte) error {
s := NewEasyStream(0, b)
return obj.Stream(s)
}
func Serialize(obj Serializable) ([]byte, error) {
s := NewEasyStream(1, []byte{})
err := obj.Stream(s)
if err != nil {
return nil, err
}
return s.Bytes(), nil
}
func RunErrorFunctions(funcs []func() error) error {
for _, f := range funcs {
if err := f(); err != nil {
return err
}
}
return nil
}
func StringifyStruct(s interface{}) string {
valueOf := reflect.ValueOf(s)
// Check if the input is a struct
if valueOf.Kind() != reflect.Struct {
return ""
}
// Get the type of the struct
structType := valueOf.Type()
// Initialize an empty string to store the result
result := structType.Name() + "{"
// Iterate through the fields of the struct
for i := 0; i < valueOf.NumField(); i++ {
field := valueOf.Field(i)
fieldType := structType.Field(i)
// Add the field name to the result
result += fieldType.Name + ": "
// Check if the field is a struct and recursively stringify it
if field.Kind() == reflect.Struct {
result += StringifyStruct(field.Interface())
} else {
// Convert the field value to a string and add it to the result
result += fmt.Sprintf("%v", field.Interface())
}
// Add a comma and space unless it's the last field
if i < valueOf.NumField()-1 {
result += ", "
}
}
// Close the struct representation
result += "}"
return result
}