Spaces:
Configuration error
Configuration error
| package storage | |
| import ( | |
| "context" | |
| "fmt" | |
| "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 { | |
| return filepath.Join(s.baseURL, path) | |
| } | |
| 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) | |
| fmt.Println(fullPath) | |
| return os.Remove(fullPath) | |
| } | |