add a new package - filestorage

This commit is contained in:
Dawid Wysokiński 2021-02-28 15:01:30 +01:00
parent 8fae4a2b03
commit 17c0d6c4e5
3 changed files with 65 additions and 0 deletions

11
pkg/filestorage/config.go Normal file
View File

@ -0,0 +1,11 @@
package filestorage
type Config struct {
BasePath string
}
func getDefaultConfig() *Config {
return &Config{
BasePath: "./",
}
}

View File

@ -0,0 +1,46 @@
package filestorage
import (
"io"
"os"
"path"
"github.com/pkg/errors"
)
type fileStorage struct {
basePath string
}
func New(cfg *Config) FileStorage {
if cfg == nil {
cfg = getDefaultConfig()
}
return &fileStorage{
cfg.BasePath,
}
}
func (storage *fileStorage) Put(file io.Reader, filename string) error {
fullPath := path.Join(storage.basePath, filename)
f, err := os.Create(fullPath)
if err != nil {
return errors.Wrap(err, "FileStorage.Put")
}
defer f.Close()
_, err = io.Copy(f, file)
if err != nil {
return errors.Wrap(err, "FileStorage.Put")
}
return nil
}
func (storage *fileStorage) Delete(filename string) error {
fullPath := path.Join(storage.basePath, filename)
err := os.Remove(fullPath)
if err != nil {
return errors.Wrap(err, "FileStorage.Delete")
}
return nil
}

View File

@ -0,0 +1,8 @@
package filestorage
import "io"
type FileStorage interface {
Put(file io.Reader, filename string) error
Delete(filename string) error
}