-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathserializers.go
95 lines (73 loc) · 2.27 KB
/
serializers.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
package shuttle
import (
"encoding/json"
"encoding/xml"
"io"
)
type jsonDeserializer struct{}
func newJSONDeserializer() Deserializer { return &jsonDeserializer{} }
func (this *jsonDeserializer) Deserialize(target any, source io.Reader) error {
if err := json.NewDecoder(source).Decode(target); err == nil {
return nil
} else if err == io.EOF {
return nil
} else {
return ErrDeserializationFailure
}
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
type jsonSerializer struct {
encoder *json.Encoder
target struct{ io.Writer }
}
func newJSONSerializer() Serializer {
this := &jsonSerializer{}
this.encoder = json.NewEncoder(&this.target)
return this
}
func (this *jsonSerializer) Serialize(target io.Writer, source any) error {
this.target.Writer = target
if this.encoder.Encode(source) == nil {
return nil
}
this.encoder = json.NewEncoder(&this.target)
return ErrSerializationFailure
}
func (this *jsonSerializer) ContentType() string { return mimeTypeApplicationJSONUTF8 }
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
type xmlDeserializer struct {
decoder *xml.Decoder
source struct{ io.Reader }
}
func newXMLDeserializer() Deserializer {
this := &xmlDeserializer{}
this.decoder = xml.NewDecoder(&this.source)
return this
}
func (this *xmlDeserializer) Deserialize(target any, source io.Reader) error {
this.source.Reader = source
if this.decoder.Decode(target) == nil {
return nil
}
this.decoder = xml.NewDecoder(&this.source)
return ErrDeserializationFailure
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
type xmlSerializer struct {
encoder *xml.Encoder
target struct{ io.Writer }
}
func newXMLSerializer() Serializer {
this := &xmlSerializer{}
this.encoder = xml.NewEncoder(&this.target)
return this
}
func (this *xmlSerializer) Serialize(target io.Writer, source any) error {
this.target.Writer = target
if this.encoder.Encode(source) == nil {
return nil
}
this.encoder = xml.NewEncoder(&this.target)
return ErrSerializationFailure
}
func (this *xmlSerializer) ContentType() string { return mimeTypeApplicationXMLUTF8 }