This repository has been archived by the owner on Jun 21, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathreader.go
93 lines (74 loc) · 1.73 KB
/
reader.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
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
package warc
import (
"fmt"
"os"
"go.etcd.io/bbolt"
)
// Archive is the storage for archiving the web page.
type Archive struct {
db *bbolt.DB
}
// Open opens the archive from specified path.
func Open(path string) (*Archive, error) {
// Make sure archive exists
info, err := os.Stat(path)
if os.IsNotExist(err) || info.IsDir() {
return nil, fmt.Errorf("archive doesn't exist")
}
// Open database
options := &bbolt.Options{
ReadOnly: true,
}
db, err := bbolt.Open(path, os.ModePerm, options)
if err != nil {
return nil, err
}
return &Archive{db: db}, nil
}
// Close closes the storage.
func (arc *Archive) Close() {
arc.db.Close()
}
// Read fetch the resource with specified name from archive.
func (arc *Archive) Read(name string) ([]byte, string, error) {
// Make sure name exists
if name == "" {
name = "archive-root"
}
var content []byte
var strContentType string
err := arc.db.View(func(tx *bbolt.Tx) error {
bucket := tx.Bucket([]byte(name))
if bucket == nil {
return fmt.Errorf("%s doesn't exist", name)
}
contentType := bucket.Get([]byte("type"))
if contentType == nil {
return fmt.Errorf("%s doesn't exist", name)
}
strContentType = string(contentType)
content = bucket.Get([]byte("content"))
if content == nil {
return fmt.Errorf("%s doesn't exist", name)
}
return nil
})
if err != nil {
return nil, "", err
}
return content, strContentType, nil
}
// HasResource checks if the resource exists in archive.
func (arc *Archive) HasResource(name string) bool {
// Make sure name exists
if name == "" {
name = "archive-root"
}
var exists bool
arc.db.View(func(tx *bbolt.Tx) error {
bucket := tx.Bucket([]byte(name))
exists = bucket != nil
return nil
})
return exists
}