Spaces:
Configuration error
Configuration error
File size: 1,368 Bytes
7beb700 decc167 7beb700 decc167 7beb700 decc167 7beb700 decc167 7beb700 decc167 7beb700 decc167 7beb700 decc167 7beb700 decc167 7beb700 decc167 7beb700 decc167 7beb700 decc167 7beb700 decc167 7beb700 decc167 7beb700 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 | package storage
import (
"context"
"io"
"os"
"path/filepath"
"strings"
)
type LocalStorage struct {
*BaseStorage
basePath string
baseURL string
}
func NewLocalStorage(basePath, baseURL string) *LocalStorage {
return &LocalStorage{
BaseStorage: NewBaseStorage(),
basePath: basePath,
baseURL: baseURL,
}
}
func (s *LocalStorage) Upload(ctx context.Context, file io.ReadSeeker, path string) error {
fullPath := filepath.Join(s.basePath, path)
dir := filepath.Dir(fullPath)
if err := os.MkdirAll(dir, 0755); err != nil {
return err
}
dst, err := os.Create(fullPath)
if err != nil {
return err
}
defer dst.Close()
if _, err := io.Copy(dst, file); err != nil {
return err
}
return nil
}
func (s *LocalStorage) GetURL(path string) string {
urlBuilder := strings.Builder{}
urlBuilder.Write([]byte(s.baseURL))
urlBuilder.Write([]byte(path))
return urlBuilder.String()
}
func (s *LocalStorage) Delete(ctx context.Context, path string) error {
// Contoh input: "http://localhost:8080/storage/users/5/profile/filename.png"
// Ambil bagian setelah "/storage/"
const prefix = "/storage/"
idx := strings.Index(path, prefix)
if idx == -1 {
return os.ErrNotExist
}
relativePath := path[idx+len(prefix):]
// Gabungkan dengan basePath
fullPath := filepath.Join(s.basePath, relativePath)
return os.Remove(fullPath)
}
|