-
Notifications
You must be signed in to change notification settings - Fork 0
/
marshal.go
72 lines (57 loc) · 1.48 KB
/
marshal.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
// Copyright (c) VirtualTam
// SPDX-License-Identifier: MIT
package opml
import (
"bufio"
"bytes"
"encoding/xml"
"io"
"os"
"strings"
"golang.org/x/net/html/charset"
)
// Marshal returns the XML encoding of a Document.
func Marshal(d *Document) ([]byte, error) {
var buf bytes.Buffer
writer := bufio.NewWriter(&buf)
_, err := writer.WriteString(xml.Header)
if err != nil {
return []byte{}, err
}
encoder := xml.NewEncoder(writer)
encoder.Indent("", " ")
if err := encoder.Encode(d); err != nil {
return []byte{}, err
}
return buf.Bytes(), nil
}
// Unmarshal unmarshals a []byte representation of an OPML file and returns the
// corresponding Document.
func Unmarshal(buf []byte) (*Document, error) {
r := bytes.NewReader(buf)
return unmarshal(r)
}
// UnmarshalFile unmarshals an OPML file and returns the corresponding Document.
func UnmarshalFile(filePath string) (*Document, error) {
file, err := os.Open(filePath)
if err != nil {
return &Document{}, err
}
defer file.Close()
return unmarshal(file)
}
// Unmarshal unmarshals a string representation of an OPML file and returns the
// corresponding Document.
func UnmarshalString(data string) (*Document, error) {
r := strings.NewReader(data)
return unmarshal(r)
}
func unmarshal(r io.Reader) (*Document, error) {
decoder := xml.NewDecoder(r)
decoder.CharsetReader = charset.NewReaderLabel
document := &Document{}
if err := decoder.Decode(document); err != nil {
return &Document{}, err
}
return document, nil
}