weather/internal/storage/file.go

55 lines
1.1 KiB
Go

package storage
import (
"go/weather/pkg/logger"
"io"
"io/fs"
"os"
"go.uber.org/zap"
)
//s3Storage classe used to store oi.Reader to s3
type fileStorage struct {
logger *logger.WeatherLogger
filename string
}
//NewFileStorage instanciate storage object
func NewFileStorage(log *logger.WeatherLogger, filename string) Storage {
s3 := fileStorage{
logger: log,
filename: filename,
}
return &s3
}
//Store send data to s3 bucket
func (ss *fileStorage) Store(content io.Reader) {
b, err := io.ReadAll(content)
ss.handleError(err)
err = AppendFile(ss.filename, append(b, "\n"...), fs.ModeAppend)
ss.handleError(err)
}
//AppendFile add line to an existing file
func AppendFile(filename string, data []byte, perm fs.FileMode) error {
f, err := os.OpenFile(filename, os.O_APPEND|os.O_WRONLY, perm)
if err != nil {
return err
}
_, err = f.Write(data)
if err1 := f.Close(); err1 != nil && err == nil {
err = err1
}
return err
}
//handleError generic fatal error
func (ss *fileStorage) handleError(err error) {
if err != nil {
ss.logger.Fatal("Storage error", zap.Error(err))
}
}