-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathxml.go
63 lines (51 loc) · 1.33 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
package render
import (
"encoding/xml"
"fmt"
"io"
)
// XMLDefualtIndent is the default indentation string used by XML instances when
// pretty rendering if no Indent value is set.
var XMLDefualtIndent = " "
// XML is a Renderer that marshals a value to XML.
type XML struct {
// Prefix is the prefix added to each level of indentation when pretty
// rendering.
Prefix string
// Indent is the string added to each level of indentation when pretty
// rendering. If empty, XMLDefualtIndent be used.
Indent string
}
var (
_ Handler = (*XML)(nil)
_ PrettyHandler = (*XML)(nil)
_ FormatsHandler = (*XML)(nil)
)
// Render marshals the given value to XML.
func (x *XML) Render(w io.Writer, v any) error {
err := xml.NewEncoder(w).Encode(v)
if err != nil {
return fmt.Errorf("%w: %w", ErrFailed, err)
}
return nil
}
// RenderPretty marshals the given value to XML with line breaks and
// indentation.
func (x *XML) RenderPretty(w io.Writer, v any) error {
prefix := x.Prefix
indent := x.Indent
if indent == "" {
indent = XMLDefualtIndent
}
enc := xml.NewEncoder(w)
enc.Indent(prefix, indent)
err := enc.Encode(v)
if err != nil {
return fmt.Errorf("%w: %w", ErrFailed, err)
}
return nil
}
// Formats returns a list of format strings that this Handler supports.
func (x *XML) Formats() []string {
return []string{"xml"}
}