Skip to content

Commit

Permalink
Add DownloadFile method interface
Browse files Browse the repository at this point in the history
  • Loading branch information
mushoffa committed Mar 19, 2022
1 parent adcff1d commit 380e6fe
Showing 1 changed file with 23 additions and 5 deletions.
28 changes: 23 additions & 5 deletions google/storage.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import (
"context"
"fmt"
"io"
"io/ioutil"
"log"
"mime/multipart"
"time"
Expand All @@ -15,7 +16,7 @@ type CloudStorageService interface {
GetInstance() *storage.Client
CreateBucket(string) error
UploadFile(multipart.File, string, string) error
DownloadFile() error
DownloadFile(string, string) ([]byte, error)
}

type storage struct {
Expand All @@ -24,7 +25,7 @@ type storage struct {
bucket string
}

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

defer client.Close()

return &storage{client, projectID, bucketName}, nil
return &storage{client, projectID}, nil
}

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

func (g *storage) DownloadFile() error {
return nil
func (g *storage) DownloadFile(bucketName, fileName string) ([]byte, error) {
ctx := context.Background()

ctx, cancel := context.WithTimeout(ctx, time.Second*50)
defer cancel()

rc, err := g.client.Bucket(bucketName).Object(fileName).NewReader(ctx)
if err != nil {
return nil, err
}

defer rc.Close()

dataFile, err := ioutil.ReadAll(rc)
if err != nil {
return nil, err
}

return dataFile nil
}

0 comments on commit 380e6fe

Please sign in to comment.