-
Notifications
You must be signed in to change notification settings - Fork 0
/
local.go
91 lines (70 loc) · 1.82 KB
/
local.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
package localstorage
import (
"io"
"io/ioutil"
"net/http"
"os"
"path"
"github.com/go-chi/chi"
"github.com/pkg/errors"
)
type LocalStorage struct {
urlPrefix string
folder string
}
func New(folder, urlPrefix string) (*LocalStorage, error) {
err := os.MkdirAll(folder, os.ModePerm)
if err != nil {
return nil, errors.Wrap(err, "could not create storage folder")
}
return &LocalStorage{
urlPrefix: urlPrefix,
folder: folder,
}, nil
}
func (ls *LocalStorage) URL(name string) (string, error) {
return ls.urlPrefix + "/" + name, nil
}
func (ls LocalStorage) getPathName(name string) string {
return path.Join(ls.folder, name)
}
func (ls *LocalStorage) Save(name string, input io.Reader) error {
pathName := ls.getPathName(name)
f, err := os.Create(pathName)
if err != nil {
return errors.Wrapf(err, "could not create file %s", pathName)
}
defer f.Close()
_, err = io.Copy(f, input)
if err != nil {
return errors.Wrap(err, "could not copy to file")
}
return nil
}
func (ls *LocalStorage) Delete(name string) error {
pathName := ls.getPathName(name)
if err := os.Remove(pathName); err != nil {
return errors.Wrapf(err, "could not delete file %s", pathName)
}
return nil
}
func (ls *LocalStorage) List(prefix string) ([]string, error) {
files, err := ioutil.ReadDir(path.Join(ls.folder, prefix))
if err != nil {
return nil, errors.Wrap(err, "could not read dir")
}
results := make([]string, len(files))
for i, file := range files {
results[i] = path.Join(ls.folder, prefix, file.Name())
}
return results, nil
}
func (ls *LocalStorage) ServeMux() http.Handler {
router := chi.NewRouter()
router.Get("/{filename}", func(w http.ResponseWriter, r *http.Request) {
name := chi.URLParam(r, "filename")
pathName := ls.getPathName(name)
http.ServeFile(w, r, pathName)
})
return router
}