-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathxml.go
More file actions
85 lines (73 loc) · 2.22 KB
/
Copy pathxml.go
File metadata and controls
85 lines (73 loc) · 2.22 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
79
80
81
82
83
84
85
// Copyright 2026 The Nanoninja Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package render
import (
"context"
"encoding/xml"
"fmt"
"io"
)
// XMLConfig defines configuration options for XML rendering.
// It allows customization of escaping, indentation, and XML header inclusion.
type XMLConfig struct {
// Prefix specifies the string to prepend at the start of each line.
// This is particularly useful when embedding XML within another format.
Prefix string
// Indent specifies the string used for each level of indentation.
// Common values are spaces (" ") or tabs ("\t").
Indent string
// Header controls whether to include the XML declaration at the start.
// When true, adds <?xml version="1.0" encoding="UTF-8"?>.
Header bool
}
// xmlRenderer implements XML rendering with configurable formatting options.
// It supports both compact and pretty-printed output formats.
type xmlRenderer struct {
config XMLConfig
}
// XML creates a new XMLRenderer with safe default configuration.
// Default settings include:
// - Standard 2-space indentation
// - XML header included
// This is the recommended constructor for most use cases.
func XML() Renderer {
return NewXML(XMLConfig{
Indent: " ", // Standard 2-space indentation
Header: true, // Include XML header by default
})
}
// NewXML creates a XMLRenderer with custom configuration.
// Use this when you need specific XML behaviors different from defaults.
func NewXML(c XMLConfig) Renderer {
return &xmlRenderer{config: c}
}
func (r xmlRenderer) ContentType() string {
return ContentTypeXML
}
func (r *xmlRenderer) Render(ctx context.Context, w io.Writer, data any, opts Options) error {
if err := CheckContext(ctx); err != nil {
return err
}
if r.config.Header {
if _, err := io.WriteString(w, xml.Header); err != nil {
return err
}
}
encoder := xml.NewEncoder(w)
if opts.Pretty {
prefix := r.config.Prefix
indent := r.config.Indent
if opts.Prefix != "" {
prefix = opts.Prefix
}
if opts.Indent != "" {
indent = opts.Indent
}
encoder.Indent(prefix, indent)
}
if err := encoder.Encode(data); err != nil {
return fmt.Errorf("xml: %w", err)
}
return nil
}