-
Notifications
You must be signed in to change notification settings - Fork 0
/
marshal.go
61 lines (50 loc) · 1.49 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
// Package netscape provides utilities to parse and export Web bookmarks using
// the Netscape Bookmark format.
package netscape
import (
"bytes"
"io"
"os"
"strings"
"github.com/virtualtam/netscape-go/decoder"
"github.com/virtualtam/netscape-go/encoder"
"github.com/virtualtam/netscape-go/parser"
"github.com/virtualtam/netscape-go/types"
)
// Marshal returns the Netscape Bookmark encoding of d.
func Marshal(d *types.Document) ([]byte, error) {
var buf bytes.Buffer
if err := encoder.NewEncoder(&buf).Encode(d); err != nil {
return []byte{}, err
}
return buf.Bytes(), nil
}
// Unmarshal unmarshals a []byte representation of a Netscape Bookmark
// file and returns the corresponding Document.
func Unmarshal(b []byte) (*types.Document, error) {
r := bytes.NewReader(b)
return unmarshal(r)
}
// UnmarshalFile unmarshals a Netscape Bookmark file and returns the
// corresponding Document.
func UnmarshalFile(filePath string) (*types.Document, error) {
file, err := os.Open(filePath)
if err != nil {
return &types.Document{}, err
}
defer file.Close()
return unmarshal(file)
}
// UnmarshalString unmarshals a string representation of a Netscape Bookmark
// file and returns the corresponding Document.
func UnmarshalString(data string) (*types.Document, error) {
r := strings.NewReader(data)
return unmarshal(r)
}
func unmarshal(r io.ReadSeeker) (*types.Document, error) {
astFile, err := parser.Parse(r)
if err != nil {
return &types.Document{}, err
}
return decoder.Decode(*astFile)
}