2020-08-23 01:06:29 +03:00
|
|
|
package storage
|
|
|
|
|
|
|
|
import (
|
|
|
|
"encoding/json"
|
|
|
|
"github.com/Lukaesebrot/pasty/internal/env"
|
|
|
|
"github.com/Lukaesebrot/pasty/internal/pastes"
|
|
|
|
"io/ioutil"
|
|
|
|
"os"
|
|
|
|
"path/filepath"
|
|
|
|
)
|
|
|
|
|
|
|
|
// FileDriver represents the file storage driver
|
|
|
|
type FileDriver struct {
|
2020-08-24 20:18:05 +03:00
|
|
|
filePath string
|
2020-08-23 01:06:29 +03:00
|
|
|
}
|
|
|
|
|
|
|
|
// Initialize initializes the file storage driver
|
|
|
|
func (driver *FileDriver) Initialize() error {
|
2020-08-24 20:18:05 +03:00
|
|
|
driver.filePath = env.Get("STORAGE_FILE_PATH", "./data")
|
|
|
|
return os.MkdirAll(driver.filePath, os.ModePerm)
|
2020-08-23 01:06:29 +03:00
|
|
|
}
|
|
|
|
|
|
|
|
// Terminate terminates the file storage driver (does nothing, because the file storage driver does not need any termination)
|
|
|
|
func (driver *FileDriver) Terminate() error {
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
2020-08-24 00:44:47 +03:00
|
|
|
// Get loads a paste
|
2020-08-24 21:22:53 +03:00
|
|
|
func (driver *FileDriver) Get(id string) (*pastes.Paste, error) {
|
2020-08-23 01:06:29 +03:00
|
|
|
// Read the file
|
2020-08-24 21:22:53 +03:00
|
|
|
data, err := ioutil.ReadFile(filepath.Join(driver.filePath, id+".json"))
|
2020-08-23 01:06:29 +03:00
|
|
|
if err != nil {
|
2020-08-23 01:32:46 +03:00
|
|
|
if os.IsNotExist(err) {
|
|
|
|
return nil, nil
|
|
|
|
}
|
2020-08-23 01:06:29 +03:00
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
|
|
|
|
// Unmarshal the file into a paste
|
|
|
|
paste := new(pastes.Paste)
|
|
|
|
err = json.Unmarshal(data, &paste)
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
return paste, nil
|
|
|
|
}
|
|
|
|
|
2020-08-24 00:44:47 +03:00
|
|
|
// Save saves a paste
|
2020-08-23 01:06:29 +03:00
|
|
|
func (driver *FileDriver) Save(paste *pastes.Paste) error {
|
|
|
|
// Marshal the paste
|
|
|
|
jsonBytes, err := json.Marshal(paste)
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
|
|
|
// Create the file to save the paste to
|
2020-08-24 21:22:53 +03:00
|
|
|
file, err := os.Create(filepath.Join(driver.filePath, paste.ID+".json"))
|
2020-08-23 01:06:29 +03:00
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
defer file.Close()
|
|
|
|
|
|
|
|
// Write the JSON data into the file
|
|
|
|
_, err = file.Write(jsonBytes)
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
|
|
|
// Delete deletes a paste
|
2020-08-24 21:22:53 +03:00
|
|
|
func (driver *FileDriver) Delete(id string) error {
|
|
|
|
return os.Remove(filepath.Join(driver.filePath, id+".json"))
|
2020-08-23 01:06:29 +03:00
|
|
|
}
|