-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathxml.go
71 lines (57 loc) · 1.55 KB
/
xml.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
package requests
import (
"bytes"
"encoding/xml"
"io"
)
// XMLEncoder handles encoding of XML data.
type XMLEncoder struct {
MarshalFunc func(v any) ([]byte, error)
}
// Encode marshals the provided value into XML format.
func (e *XMLEncoder) Encode(v any) (io.Reader, error) {
var err error
var data []byte
if e.MarshalFunc != nil {
data, err = e.MarshalFunc(v)
} else {
data, err = xml.Marshal(v) // Fallback to standard XML marshal if no custom function is provided
}
if err != nil {
return nil, err
}
buf := GetBuffer()
_, err = buf.Write(data)
if err != nil {
PutBuffer(buf)
return nil, 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 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
}
// 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 err
}
if d.UnmarshalFunc != nil {
return d.UnmarshalFunc(data, v)
}
return xml.Unmarshal(data, v) // Fallback to standard XML unmarshal
}
// DefaultXMLDecoder instance using the standard xml.Unmarshal function
var DefaultXMLDecoder = &XMLDecoder{
UnmarshalFunc: xml.Unmarshal,
}