-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserialize.go
102 lines (88 loc) · 2.33 KB
/
serialize.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
package serializer
import (
"encoding/csv"
"encoding/json"
"encoding/xml"
"fmt"
"github.com/philiphil/serializer/Filter"
"reflect"
"strings"
)
func (s *Serializer) Serialize(obj any, groups ...string) (string, error) {
switch s.Format {
case JSON:
return s.serializeJSON(obj, groups...)
case XML:
return s.serializeXML(obj, groups...)
case CSV:
return s.serializeCSV(obj, groups...)
default:
return "", fmt.Errorf("Unsupported format: %s", s.Format)
}
}
func (s *Serializer) serializeJSON(obj any, groups ...string) (string, error) {
data := Filter.FilterByGroups(obj, groups...)
//data = renameFieldsToLower(data)
jsonBytes, err := json.MarshalIndent(data, "", " ")
if err != nil {
return "", err
}
return string(jsonBytes), nil
}
func (s *Serializer) serializeXML(obj any, groups ...string) (string, error) {
data := Filter.FilterByGroups(obj, groups...)
xmlBytes, err := xml.MarshalIndent(data, "", " ")
if err != nil {
return "", err
}
return string(xmlBytes), nil
}
func (s *Serializer) serializeCSV(obj any, groups ...string) (string, error) {
data := Filter.FilterByGroups(obj, groups...)
value := reflect.ValueOf(data)
if value.Kind() != reflect.Slice {
return "", fmt.Errorf("Invalid object type for CSV serialization")
}
rows := make([][]string, 0)
header := make([]string, 0)
for i := 0; i < value.Len(); i++ {
row := make([]string, 0)
elem := value.Index(i).Interface()
elemValue := reflect.ValueOf(elem)
// Handle header row
if i == 0 {
for j := 0; j < elemValue.NumField(); j++ {
field := elemValue.Type().Field(j)
if Filter.IsFieldIncluded(field, groups) {
header = append(header, field.Name)
}
}
rows = append(rows, header)
}
for j := 0; j < elemValue.NumField(); j++ {
field := elemValue.Field(j)
if Filter.IsFieldIncluded(elemValue.Type().Field(j), groups) {
row = append(row, fmt.Sprintf("%v", field.Interface()))
}
}
rows = append(rows, row)
}
csvBytes, err := writeCSVToString(rows)
if err != nil {
return "", err
}
return string(csvBytes), nil
}
func writeCSVToString(rows [][]string) ([]byte, error) {
sb := strings.Builder{}
writer := csv.NewWriter(&sb)
err := writer.WriteAll(rows)
if err != nil {
return nil, err
}
writer.Flush()
if err := writer.Error(); err != nil {
return nil, err
}
return []byte(sb.String()), nil
}