Skip to content

Commit 380e6fe

Browse files
committed
Add DownloadFile method interface
1 parent adcff1d commit 380e6fe

File tree

1 file changed

+23
-5
lines changed

1 file changed

+23
-5
lines changed

google/storage.go

Lines changed: 23 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@ import (
44
"context"
55
"fmt"
66
"io"
7+
"io/ioutil"
78
"log"
89
"mime/multipart"
910
"time"
@@ -15,7 +16,7 @@ type CloudStorageService interface {
1516
GetInstance() *storage.Client
1617
CreateBucket(string) error
1718
UploadFile(multipart.File, string, string) error
18-
DownloadFile() error
19+
DownloadFile(string, string) ([]byte, error)
1920
}
2021

2122
type storage struct {
@@ -24,7 +25,7 @@ type storage struct {
2425
bucket string
2526
}
2627

27-
func NewCloudStorageClient(projectID, bucketName string) (CloudStorageService, error) {
28+
func NewCloudStorageClient(projectID string) (CloudStorageService, error) {
2829
// Creates Google Cloud Storage client agent
2930
client, err := storage.NewClient(context.Background())
3031
if err != nil {
@@ -33,7 +34,7 @@ func NewCloudStorageClient(projectID, bucketName string) (CloudStorageService, e
3334

3435
defer client.Close()
3536

36-
return &storage{client, projectID, bucketName}, nil
37+
return &storage{client, projectID}, nil
3738
}
3839

3940
func (g *storage) GetInstance() *storage.Client {
@@ -79,6 +80,23 @@ func (g *storage) UploadFile(file multipart.File, folderName, fileName string) e
7980
return nil
8081
}
8182

82-
func (g *storage) DownloadFile() error {
83-
return nil
83+
func (g *storage) DownloadFile(bucketName, fileName string) ([]byte, error) {
84+
ctx := context.Background()
85+
86+
ctx, cancel := context.WithTimeout(ctx, time.Second*50)
87+
defer cancel()
88+
89+
rc, err := g.client.Bucket(bucketName).Object(fileName).NewReader(ctx)
90+
if err != nil {
91+
return nil, err
92+
}
93+
94+
defer rc.Close()
95+
96+
dataFile, err := ioutil.ReadAll(rc)
97+
if err != nil {
98+
return nil, err
99+
}
100+
101+
return dataFile nil
84102
}

0 commit comments

Comments
 (0)