/
filesystem.go
102 lines (80 loc) · 1.86 KB
/
filesystem.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
92
93
94
95
96
97
98
99
100
101
102
package storage
import (
"io/ioutil"
"os"
"path/filepath"
"strconv"
"strings"
"sync"
)
func init() {
SupportedStorageTypes["Filesystem"] = new(interface{})
}
type Filesystem struct {
Root string
c uint64
mu sync.RWMutex
}
func NewFilesystem(root string) (*Filesystem, error) {
s := &Filesystem{
Root: root,
}
return s, os.MkdirAll(s.Root, 0744)
}
func (s *Filesystem) Code(url string) string {
return strconv.FormatUint(s.c, 36)
}
func (s *Filesystem) Save(url string) (string, error) {
if _, err := validateURL(url); err != nil {
return "", err
}
code := s.Code(url)
s.mu.Lock()
err := ioutil.WriteFile(filepath.Join(s.Root, code), []byte(url), 0744)
if err == nil {
s.c++
}
s.mu.Unlock()
return code, err
}
// CleanPath removes any path transversal nonsense
func CleanPath(path string) string {
if !strings.HasPrefix(path, "/") {
path = "/" + path
}
return filepath.Clean(path)
}
// Takes a possibly multilevel path and flattens it by dropping any slashes
func FlattenPath(path string, separator string) string {
return strings.Replace(path, string(os.PathSeparator), separator, -1)
}
func (s *Filesystem) SaveName(rawShort, url string) error {
short, err := sanitizeShort(rawShort)
if err != nil {
return err
}
if _, err := validateURL(url); err != nil {
return err
}
short = FlattenPath(CleanPath(short), "_")
s.mu.Lock()
if err := ioutil.WriteFile(filepath.Join(s.Root, short), []byte(url), 0744); err == nil {
s.c++
}
s.mu.Unlock()
return err
}
func (s *Filesystem) Load(rawShort string) (string, error) {
short, err := sanitizeShort(rawShort)
if err != nil {
return "", err
}
short = FlattenPath(CleanPath(short), "_")
s.mu.Lock()
urlBytes, err := ioutil.ReadFile(filepath.Join(s.Root, short))
s.mu.Unlock()
if _, ok := err.(*os.PathError); ok {
return "", ErrShortNotSet
}
return string(urlBytes), err
}