96 lines
1.7 KiB
Go
96 lines
1.7 KiB
Go
package sysStorage
|
|
|
|
import (
|
|
"bytes"
|
|
"donat-widget/internal/model"
|
|
"io"
|
|
"os"
|
|
"path/filepath"
|
|
)
|
|
|
|
type LocalStorage struct {
|
|
basePath string
|
|
}
|
|
|
|
func NewLocalStorage(basePath string) *LocalStorage {
|
|
if basePath == "" {
|
|
var err error
|
|
basePath, err = os.Getwd()
|
|
if err != nil {
|
|
panic("Failed to get current directory: " + err.Error())
|
|
}
|
|
}
|
|
|
|
if err := os.MkdirAll(basePath, os.ModePerm); err != nil {
|
|
panic("Failed to create storage directory: " + err.Error())
|
|
}
|
|
return &LocalStorage{basePath: basePath}
|
|
}
|
|
|
|
func (ls *LocalStorage) Upload(
|
|
file model.UploadFile,
|
|
filename string,
|
|
size int64,
|
|
collection string,
|
|
) (model.FileID, error) {
|
|
collectionPath := filepath.Join(ls.basePath, collection)
|
|
if err := os.MkdirAll(collectionPath, os.ModePerm); err != nil {
|
|
return "error", err
|
|
}
|
|
|
|
filePath := filepath.Join(collectionPath, filename)
|
|
f, err := os.Create(filePath)
|
|
if err != nil {
|
|
return "error creating", err
|
|
}
|
|
defer f.Close()
|
|
|
|
_, err = io.Copy(f, *file)
|
|
if err != nil {
|
|
return "error copy", err
|
|
}
|
|
|
|
return model.FileID(filename), nil
|
|
}
|
|
|
|
func (ls *LocalStorage) Download(
|
|
FileID model.FileID,
|
|
) (model.DownloadFile, error) {
|
|
filePath := string(FileID)
|
|
f, err := os.Open(filePath)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
defer f.Close()
|
|
|
|
var fileBuffer bytes.Buffer
|
|
_, err = io.Copy(&fileBuffer, f)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
|
|
return fileBuffer.Bytes(), nil
|
|
}
|
|
|
|
func (ls *LocalStorage) Update(
|
|
file model.UploadFile,
|
|
fileID model.FileID,
|
|
filename string,
|
|
size int64,
|
|
collection string,
|
|
) error {
|
|
filePath := string(fileID)
|
|
f, err := os.Create(filePath)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
defer f.Close()
|
|
|
|
_, err = io.Copy(f, *file)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
|
|
return nil
|
|
}
|