-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathxml.go
More file actions
78 lines (64 loc) · 1.9 KB
/
xml.go
File metadata and controls
78 lines (64 loc) · 1.9 KB
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
package requests
import (
"bytes"
"encoding/xml"
"fmt"
"io"
)
// XMLEncoder handles encoding of XML data.
type XMLEncoder struct {
MarshalFunc func(v any) ([]byte, error) // MarshalFunc marshals a value into XML.
}
// Encode marshals the provided value into XML format.
func (e *XMLEncoder) Encode(v any) (io.Reader, error) {
var data []byte
var err error
if e.MarshalFunc != nil {
data, err = e.MarshalFunc(v)
} else {
data, err = xml.Marshal(v)
}
if err != nil {
return nil, fmt.Errorf("%w: %w", ErrEncodingFailed, err)
}
buf := GetBuffer()
_, err = buf.Write(data)
if err != nil {
PutBuffer(buf)
return nil, fmt.Errorf("failed to write XML to buffer: %w", err)
}
return &poolReader{Reader: bytes.NewReader(buf.B), poolBuf: buf}, nil
}
// ContentType returns the content type for XML data.
func (e *XMLEncoder) ContentType() string {
return "application/xml;charset=utf-8"
}
// DefaultXMLEncoder is the default XMLEncoder instance using the standard xml.Marshal function.
var DefaultXMLEncoder = &XMLEncoder{
MarshalFunc: xml.Marshal,
}
// XMLDecoder handles decoding of XML data.
type XMLDecoder struct {
UnmarshalFunc func(data []byte, v any) error // UnmarshalFunc unmarshals XML data into a value.
}
// Decode reads the data from the reader and unmarshals it into the provided value.
func (d *XMLDecoder) Decode(r io.Reader, v any) error {
data, err := io.ReadAll(r)
if err != nil {
return fmt.Errorf("failed to read XML data: %w", err)
}
if d.UnmarshalFunc != nil {
if err := d.UnmarshalFunc(data, v); err != nil {
return fmt.Errorf("failed to unmarshal XML: %w", err)
}
return nil
}
if err := xml.Unmarshal(data, v); err != nil {
return fmt.Errorf("failed to unmarshal XML: %w", err)
}
return nil
}
// DefaultXMLDecoder is the default XMLDecoder instance using the standard xml.Unmarshal function.
var DefaultXMLDecoder = &XMLDecoder{
UnmarshalFunc: xml.Unmarshal,
}