add delete func, add check for invalid local paths

This commit is contained in:
Shane C. 2024-11-18 16:48:49 -05:00
parent 41e7d6070d
commit 9614599eb5
Signed by: Shane C.
GPG key ID: E46B5FEA35B22FF9
2 changed files with 27 additions and 3 deletions

View file

@ -7,6 +7,7 @@ import (
"github.com/minio/minio-go/v7" "github.com/minio/minio-go/v7"
"github.com/minio/minio-go/v7/pkg/credentials" "github.com/minio/minio-go/v7/pkg/credentials"
"io" "io"
"io/fs"
"net/http" "net/http"
"os" "os"
"path/filepath" "path/filepath"
@ -68,8 +69,14 @@ func New(config *Config) (*Storage, error) {
newStorage.s3Client = s3Client newStorage.s3Client = s3Client
case "local": case "local":
if err := os.MkdirAll(config.Path, 0740); err != nil { if statInfo, err := os.Stat(config.Path); err != nil && errors.Is(err, fs.ErrNotExist) {
if err := os.MkdirAll(config.Path, 0740); err != nil {
return nil, err
}
} else if err != nil {
return nil, err return nil, err
} else if statInfo.IsDir() {
return nil, ErrInvalidPath
} }
default: default:
return nil, ErrInvalidStorageType return nil, ErrInvalidStorageType
@ -164,3 +171,14 @@ func (s *Storage) Write(name string, data []byte, opts WriteOptions) error {
return os.WriteFile(filepath.Join(s.config.Path, name), data, 0640) return os.WriteFile(filepath.Join(s.config.Path, name), data, 0640)
} }
} }
func (s *Storage) Delete(name string) error {
if s.s3Client != nil {
if err := s.s3Client.RemoveObject(s.ctx, s.config.S3BucketName, name, minio.RemoveObjectOptions{}); err != nil {
return err
}
return nil
} else {
return os.Remove(filepath.Join(s.config.Path, name))
}
}

View file

@ -1,7 +1,6 @@
package fsys package fsys
import ( import (
"fmt"
"github.com/stretchr/testify/assert" "github.com/stretchr/testify/assert"
"io" "io"
"testing" "testing"
@ -36,6 +35,10 @@ func TestStorageLocal(t *testing.T) {
err = file.Close() err = file.Close()
assert.NoError(t, err) assert.NoError(t, err)
t.Log("== Delete ==")
err = stor.Delete("test.txt")
assert.NoError(t, err)
} }
func TestStorageS3(t *testing.T) { func TestStorageS3(t *testing.T) {
@ -56,7 +59,6 @@ func TestStorageS3(t *testing.T) {
t.Log("== Read ==") t.Log("== Read ==")
fileContent, err := stor.Read("test.txt") fileContent, err := stor.Read("test.txt")
assert.NoError(t, err) assert.NoError(t, err)
fmt.Println(fileContent)
assert.Equal(t, []byte("hi"), fileContent) assert.Equal(t, []byte("hi"), fileContent)
t.Log("== Open ==") t.Log("== Open ==")
@ -71,4 +73,8 @@ func TestStorageS3(t *testing.T) {
err = file.Close() err = file.Close()
assert.NoError(t, err) assert.NoError(t, err)
t.Log("== Delete ==")
err = stor.Delete("test.txt")
assert.NoError(t, err)
} }