100 lines
2.1 KiB
Go
100 lines
2.1 KiB
Go
package svg
|
|
|
|
import (
|
|
"io"
|
|
"log"
|
|
"net/http"
|
|
"os"
|
|
"path/filepath"
|
|
)
|
|
|
|
type SvgStorage interface {
|
|
Create(id string, svg io.Reader) (string, error)
|
|
Get(id string) (io.ReadCloser, error)
|
|
CreatePublic(data io.Reader, filetype string) (string, error)
|
|
GetPublic(path string) (io.ReadCloser, error)
|
|
GetPublicDir() http.Dir
|
|
}
|
|
|
|
var _ SvgStorage = FileSvgStorage{}
|
|
var TempDir string = ""
|
|
|
|
type FileSvgStorage struct {
|
|
basepath, publicSubPath string
|
|
}
|
|
|
|
func NewFileStorage(path, publicSubPath string) *FileSvgStorage {
|
|
err := os.MkdirAll(path, 0755)
|
|
if err != nil {
|
|
panic(err)
|
|
}
|
|
log.Println("Initialized file storage handler")
|
|
return &FileSvgStorage{path, publicSubPath}
|
|
}
|
|
|
|
func (f FileSvgStorage) Create(id string, svg io.Reader) (string, error) {
|
|
file, err := os.Create(filepath.Join(f.basepath, id+".svg"))
|
|
|
|
if err != nil {
|
|
return "", err
|
|
}
|
|
defer file.Close()
|
|
|
|
_, err = io.Copy(file, svg)
|
|
if err != nil {
|
|
return "", err
|
|
}
|
|
|
|
log.Println("Created File: ", file.Name())
|
|
return file.Name(), nil
|
|
}
|
|
|
|
func (f FileSvgStorage) Get(id string) (io.ReadCloser, error) {
|
|
file, err := os.Open(filepath.Join(f.basepath, id+".svg"))
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
return file, nil
|
|
}
|
|
|
|
func (f FileSvgStorage) CreatePublic(data io.Reader, filetype string) (string, error) {
|
|
path := filepath.Join(f.basepath, f.publicSubPath)
|
|
if err := os.Mkdir(path, 0755); err != nil {
|
|
return "", err
|
|
}
|
|
|
|
file, err := os.CreateTemp(path, "*."+filetype)
|
|
if err != nil {
|
|
return "", err
|
|
}
|
|
defer file.Close()
|
|
|
|
return file.Name(), nil
|
|
}
|
|
|
|
func (f FileSvgStorage) GetPublic(path string) (io.ReadCloser, error) {
|
|
file, err := os.Open(filepath.Join(f.basepath, f.publicSubPath, path))
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
return file, nil
|
|
}
|
|
|
|
func (f FileSvgStorage) GetPublicDir() http.Dir {
|
|
return http.Dir(filepath.Join(f.basepath, f.publicSubPath))
|
|
}
|
|
|
|
func CreateTemp(data io.Reader, filetype string) (string, error) {
|
|
file, err := os.CreateTemp(TempDir, "*."+filetype)
|
|
if err != nil {
|
|
return "", err
|
|
}
|
|
defer file.Close()
|
|
_, err = io.Copy(file, data)
|
|
if err != nil {
|
|
return "", err
|
|
}
|
|
|
|
return file.Name(), nil
|
|
}
|