-
Notifications
You must be signed in to change notification settings - Fork 0
/
readdir.go
208 lines (191 loc) · 4.89 KB
/
readdir.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
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
package s3util
import (
"bytes"
"encoding/xml"
"errors"
"io"
"net/http"
"net/url"
"os"
"strconv"
"strings"
"time"
)
// File represents an S3 object or directory.
type File struct {
url string
prefix string
config *Config
result *listObjectsResult
}
type fileInfo struct {
name string
size int64
dir bool
modTime time.Time
sys *Stat
}
// Stat contains information about an S3 object or directory.
// It is the "underlying data source" returned by method Sys
// for each FileInfo produced by this package.
// fi.Sys().(*s3util.Stat)
// For the meaning of these fields, see
// http://docs.aws.amazon.com/AmazonS3/latest/API/RESTBucketGET.html.
type Stat struct {
Key string
LastModified string
ETag string // ETag value, without double quotes.
Size string
StorageClass string
OwnerID string `xml:"Owner>ID"`
OwnerName string `xml:"Owner>DisplayName"`
}
type listObjectsResult struct {
IsTruncated bool
Contents []Stat
Directories []string `xml:"CommonPrefixes>Prefix"` // Suffix "/" trimmed
}
func (f *fileInfo) Name() string { return f.name }
func (f *fileInfo) Size() int64 { return f.size }
func (f *fileInfo) Mode() os.FileMode {
if f.dir {
return 0755 | os.ModeDir
}
return 0644
}
func (f *fileInfo) ModTime() time.Time {
if f.modTime.IsZero() && f.sys != nil {
// we return the zero value if a parse error ever happens.
f.modTime, _ = time.Parse(time.RFC3339Nano, f.sys.LastModified)
}
return f.modTime
}
func (f *fileInfo) IsDir() bool { return f.dir }
func (f *fileInfo) Sys() interface{} { return f.sys }
// NewFile returns a new File with the given URL and config.
//
// Set rawurl to a directory on S3, such as
// https://mybucket.s3.amazonaws.com/myfolder.
// The URL cannot have query parameters or a fragment.
// If c is nil, DefaultConfig will be used.
func NewFile(rawurl string, c *Config) (*File, error) {
u, err := url.Parse(rawurl)
if err != nil {
return nil, err
}
if u.RawQuery != "" {
return nil, errors.New("url cannot have raw query parameters.")
}
if u.Fragment != "" {
return nil, errors.New("url cannot have a fragment.")
}
prefix := strings.TrimLeft(u.Path, "/")
if prefix != "" && !strings.HasSuffix(prefix, "/") {
prefix += "/"
}
u.Path = ""
return &File{u.String(), prefix, c, nil}, nil
}
// Readdir requests a list of entries in the S3 directory
// represented by f and returns a slice of up to n FileInfo
// values, in alphabetical order. Subsequent calls
// on the same File will yield further FileInfos.
// Only direct children are returned, not deeper descendants.
func (f *File) Readdir(n int) ([]os.FileInfo, error) {
if f.result != nil && !f.result.IsTruncated {
return make([]os.FileInfo, 0), io.EOF
}
reader, err := f.sendRequest(n)
if err != nil {
return nil, err
}
defer reader.Close()
return f.parseResponse(reader)
}
func (f *File) sendRequest(count int) (io.ReadCloser, error) {
c := f.config
if c == nil {
c = DefaultConfig
}
var buf bytes.Buffer
buf.WriteString(f.url)
buf.WriteString("?delimiter=%2F")
if f.prefix != "" {
buf.WriteString("&prefix=")
buf.WriteString(url.QueryEscape(f.prefix))
}
if count > 0 {
buf.WriteString("&max-keys=")
buf.WriteString(strconv.Itoa(count))
}
if f.result != nil && f.result.IsTruncated {
var lastDir, lastKey, marker string
if len(f.result.Directories) > 0 {
lastDir = f.result.Directories[len(f.result.Directories)-1]
}
if len(f.result.Contents) > 0 {
lastKey = f.result.Contents[len(f.result.Contents)-1].Key
}
if lastKey > lastDir {
marker = lastKey
} else {
marker = lastDir
}
if marker != "" {
buf.WriteString("&marker=")
buf.WriteString(url.QueryEscape(marker))
}
}
u := buf.String()
r, _ := http.NewRequest("GET", u, nil)
r.Header.Set("Date", time.Now().UTC().Format(http.TimeFormat))
c.Sign(r, *c.Keys)
resp, err := http.DefaultClient.Do(r)
if err != nil {
return nil, err
}
if resp.StatusCode != 200 {
return nil, newRespError(resp)
}
return resp.Body, nil
}
func (f *File) parseResponse(reader io.Reader) ([]os.FileInfo, error) {
decoder := xml.NewDecoder(reader)
result := listObjectsResult{}
var err error
err = decoder.Decode(&result)
if err != nil {
return nil, err
}
infos := make([]os.FileInfo, len(result.Contents)+len(result.Directories))
var size int64
var name string
var is_dir bool
for i, content := range result.Contents {
c := content
c.ETag = strings.Trim(c.ETag, `"`)
size, _ = strconv.ParseInt(c.Size, 10, 0)
if size == 0 && strings.HasSuffix(c.Key, "/") {
name = strings.TrimRight(c.Key, "/")
is_dir = true
} else {
name = c.Key
is_dir = false
}
infos[i] = &fileInfo{
name: name,
size: size,
dir: is_dir,
sys: &c,
}
}
for i, dir := range result.Directories {
infos[len(result.Contents)+i] = &fileInfo{
name: strings.TrimRight(dir, "/"),
size: 0,
dir: true,
}
}
f.result = &result
return infos, nil
}