79 lines
2.1 KiB
Go
79 lines
2.1 KiB
Go
package storage
|
|
|
|
import (
|
|
"context"
|
|
"errors"
|
|
"fmt"
|
|
"io"
|
|
"os"
|
|
"path/filepath"
|
|
"strings"
|
|
)
|
|
|
|
// LocalStorage writes uploads to a directory on disk instead of S3 — for
|
|
// STORAGE_DRIVER=local, so the app can be tested without a real S3 bucket.
|
|
// Keys are the same "users/{id}/cars/{id}/..." paths used for S3; they're
|
|
// just joined onto basePath instead of being S3 object keys.
|
|
type LocalStorage struct {
|
|
basePath string
|
|
}
|
|
|
|
func NewLocal(basePath string) (*LocalStorage, error) {
|
|
if err := os.MkdirAll(basePath, 0o755); err != nil {
|
|
return nil, fmt.Errorf("create local storage dir: %w", err)
|
|
}
|
|
return &LocalStorage{basePath: basePath}, nil
|
|
}
|
|
|
|
func (l *LocalStorage) Upload(ctx context.Context, key, contentType string, r io.Reader) error {
|
|
path, err := l.resolve(key)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
if err := os.MkdirAll(filepath.Dir(path), 0o755); err != nil {
|
|
return fmt.Errorf("create dir for %s: %w", key, err)
|
|
}
|
|
f, err := os.Create(path)
|
|
if err != nil {
|
|
return fmt.Errorf("create %s: %w", key, err)
|
|
}
|
|
defer f.Close()
|
|
if _, err := io.Copy(f, r); err != nil {
|
|
return fmt.Errorf("write %s: %w", key, err)
|
|
}
|
|
return nil
|
|
}
|
|
|
|
func (l *LocalStorage) Get(ctx context.Context, key string) (io.ReadCloser, error) {
|
|
path, err := l.resolve(key)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
f, err := os.Open(path)
|
|
if err != nil {
|
|
return nil, fmt.Errorf("open %s: %w", key, err)
|
|
}
|
|
return f, nil
|
|
}
|
|
|
|
func (l *LocalStorage) Delete(ctx context.Context, key string) error {
|
|
path, err := l.resolve(key)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
if err := os.Remove(path); err != nil && !errors.Is(err, os.ErrNotExist) {
|
|
return fmt.Errorf("delete %s: %w", key, err)
|
|
}
|
|
return nil
|
|
}
|
|
|
|
// resolve joins key onto basePath, rejecting anything that would escape it.
|
|
// Keys are always built internally from UUIDs + sanitized filenames, so
|
|
// this is defense in depth rather than a load-bearing check.
|
|
func (l *LocalStorage) resolve(key string) (string, error) {
|
|
if strings.Contains(key, "..") {
|
|
return "", fmt.Errorf("invalid storage key %q", key)
|
|
}
|
|
return filepath.Join(l.basePath, filepath.FromSlash(key)), nil
|
|
}
|