From e47ca8d35d8ae5851abde600f7ca2949e1e7b163 Mon Sep 17 00:00:00 2001 From: Haris Thohir Date: Wed, 4 Dec 2024 17:57:38 +0700 Subject: [PATCH] feat: download file --- gcs_manager.go | 20 ++++++++++++++++++++ gcs_manager_mock.go | 14 ++++++++++++++ gcs_manager_test.go | 11 +++++++++++ 3 files changed, 45 insertions(+) diff --git a/gcs_manager.go b/gcs_manager.go index 44fd0a4..1352d7b 100644 --- a/gcs_manager.go +++ b/gcs_manager.go @@ -18,6 +18,7 @@ type ( ListFiles(bucketName string) ([]string, error) MoveFile(bucketName, srcObjectName, dstObjectName string) error DeleteAllFilesInDirectory(bucketName, directory string) error + DownloadFile(bucketName, objectName, destPath string) error } gcsManager struct { @@ -118,3 +119,22 @@ func (g gcsManager) DeleteAllFilesInDirectory(bucketName, directory string) erro return nil } + +func (g gcsManager) DownloadFile(bucketName, objectName, destPath string) error { + bucket := g.client.Bucket(bucketName) + obj := bucket.Object(objectName) + r, err := obj.NewReader(g.ctx) + if err != nil { + return err + } + defer r.Close() + + out, err := os.Create(destPath) + if err != nil { + return err + } + defer out.Close() + + _, err = io.Copy(out, r) + return err +} diff --git a/gcs_manager_mock.go b/gcs_manager_mock.go index 06a3230..ab3beb8 100644 --- a/gcs_manager_mock.go +++ b/gcs_manager_mock.go @@ -62,6 +62,20 @@ func (mr *MockGCSManagerMockRecorder) DeleteFile(bucketName, objectName interfac return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "DeleteFile", reflect.TypeOf((*MockGCSManager)(nil).DeleteFile), bucketName, objectName) } +// DownloadFile mocks base method. +func (m *MockGCSManager) DownloadFile(bucketName, objectName, destPath string) error { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "DownloadFile", bucketName, objectName, destPath) + ret0, _ := ret[0].(error) + return ret0 +} + +// DownloadFile indicates an expected call of DownloadFile. +func (mr *MockGCSManagerMockRecorder) DownloadFile(bucketName, objectName, destPath interface{}) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "DownloadFile", reflect.TypeOf((*MockGCSManager)(nil).DownloadFile), bucketName, objectName, destPath) +} + // ListFiles mocks base method. func (m *MockGCSManager) ListFiles(bucketName string) ([]string, error) { m.ctrl.T.Helper() diff --git a/gcs_manager_test.go b/gcs_manager_test.go index d874df1..589c70a 100644 --- a/gcs_manager_test.go +++ b/gcs_manager_test.go @@ -71,3 +71,14 @@ func TestDeleteAllFilesInDirectory(t *testing.T) { err := mockGCS.DeleteAllFilesInDirectory("bucketName", "directory/") assert.NoError(t, err) } + +func TestDownloadFile(t *testing.T) { + ctrl := gomock.NewController(t) + defer ctrl.Finish() + + mockGCS := NewMockGCSManager(ctrl) + mockGCS.EXPECT().DownloadFile("bucketName", "directory/file.ext", "/tmp/").Return(nil) + + err := mockGCS.DownloadFile("bucketName", "directory/file.ext", "/tmp/") + assert.NoError(t, err) +}