-
Notifications
You must be signed in to change notification settings - Fork 218
/
read.go
74 lines (62 loc) · 1.78 KB
/
read.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
package amazons3
import (
"bufio"
"io/ioutil"
"os"
"path/filepath"
"strings"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/service/s3"
"github.com/aws/aws-sdk-go/service/s3/s3manager"
uuid "github.com/satori/go.uuid"
"github.com/spaceuptech/space-cloud/model"
)
// ListDir lists a directory in S3
func (a *AmazonS3) ListDir(req *model.ListFilesRequest) ([]*model.ListFilesResponse, error) {
svc := s3.New(a.client)
// Add a backslash if not there already
if !strings.HasSuffix(req.Path, "/") {
req.Path = req.Path + "/"
}
resp, _ := svc.ListObjects(&s3.ListObjectsInput{
Bucket: aws.String(a.bucket),
Prefix: aws.String(req.Path), //backslash at the end is important
Delimiter: aws.String("/"),
})
result := []*model.ListFilesResponse{}
resp.Contents = resp.Contents[1:]
for _, key := range resp.Contents {
t := &model.ListFilesResponse{Name: filepath.Base(*key.Key), Type: "file"}
if req.Type == "all" || req.Type == t.Type {
result = append(result, t)
}
}
for _, key := range resp.CommonPrefixes {
t := &model.ListFilesResponse{Name: filepath.Base(*key.Prefix), Type: "dir"}
if req.Type == "all" || req.Type == t.Type {
result = append(result, t)
}
}
return result, nil
}
// ReadFile reads a file from S3
func (a *AmazonS3) ReadFile(path string) (*model.File, error) {
u2 := uuid.NewV4()
tmpfile, err := ioutil.TempFile("", u2.String())
if err != nil {
return nil, err
}
downloader := s3manager.NewDownloader(a.client)
_, err = downloader.Download(tmpfile,
&s3.GetObjectInput{
Bucket: aws.String(a.bucket),
Key: aws.String(path),
})
if err != nil {
return nil, err
}
return &model.File{File: bufio.NewReader(tmpfile), Close: func() error {
defer os.Remove(tmpfile.Name())
return tmpfile.Close()
}}, nil
}