-
Notifications
You must be signed in to change notification settings - Fork 0
/
local.go
69 lines (55 loc) · 1.5 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
package filestorage
import (
"fmt"
"io"
"os"
"path/filepath"
"strings"
)
// Local is a local file storage.
type Local struct {
// dir is the base directory to store files.
dir string
// url is the base URL of the stored files.
url string
}
// NewLocal returns a new local file storage.
func NewLocal(dir, url string) (*Local, error) {
if err := os.MkdirAll(dir, 0777); err != nil {
return nil, fmt.Errorf("failed to create a directory (%q): %v", dir, err)
}
s := &Local{
dir: dir,
url: strings.TrimSuffix(url, "/"),
}
return s, nil
}
// Save saves data from r to file with the given path.
func (s *Local) Save(path string, r io.Reader) error {
fullpath := filepath.Join(s.dir, path)
if err := os.MkdirAll(filepath.Dir(fullpath), 0777); err != nil {
return fmt.Errorf("failed to create a directory for file (%q): %v", fullpath, err)
}
w, err := os.Create(fullpath)
if err != nil {
return fmt.Errorf("failed to create a file (%q): %v", fullpath, err)
}
defer w.Close()
_, err = io.Copy(w, r)
if err != nil {
return fmt.Errorf("failed to copy data to file (%q): %v", fullpath, err)
}
return nil
}
// Remove removes the file with the given path.
func (s *Local) Remove(path string) error {
fullpath := filepath.Join(s.dir, path)
if err := os.Remove(fullpath); err != nil {
return fmt.Errorf("failed to remove a file (%q): %v", fullpath, err)
}
return nil
}
// URL returns an URL of the file with the given path.
func (s *Local) URL(path string) string {
return s.url + "/" + path
}