/
fs.go
79 lines (71 loc) · 2.08 KB
/
fs.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
package storage
import (
"errors"
"io/fs"
"os"
"path"
"path/filepath"
"strings"
)
var (
defaultDirectoryMode os.FileMode = 0755
defaultFileMode os.FileMode = 0644
errInvalidFilePathCharacter = errors.New("invalid character in file path")
)
// Dir implements access to a collection of named files, restricted to a
// specific directory tree. It is very similar to net/http.Dir, but provides
// write access and some io/ioutil utilities.
// An empty directory is treated as ".".
type Dir string
// readFile reads data from a file at a given path, restricted to a specific
// directory tree.
func (d Dir) readFile(path string) ([]byte, error) {
path, err := d.sanitize(path)
if err != nil {
return nil, err
}
return os.ReadFile(path)
}
// readDir reads the directory named by the given path and returns a list of
// sorted directory entries. Restricted to a specified directory tree.
func (d Dir) readDir(dirname string) ([]fs.DirEntry, error) {
path, err := d.sanitize(dirname)
if err != nil {
return nil, err
}
return os.ReadDir(path)
}
// writeFile writes the data as a file at given path, restricted to a specific
// directory tree.
func (d Dir) writeFile(path string, data []byte) error {
// make parent directories as needed
path, err := d.sanitize(path)
if err != nil {
return err
}
if err := os.MkdirAll(filepath.Dir(path), defaultDirectoryMode); err != nil {
return err
}
return os.WriteFile(path, data, defaultFileMode)
}
// deleteFile removes the file at the given path, restricted to a specific
// directory tree.
func (d Dir) deleteFile(path string) error {
path, err := d.sanitize(path)
if err != nil {
return err
}
return os.Remove(path)
}
// Borrowed directly from net/http Dir.Open and FileServer.
func (d Dir) sanitize(name string) (string, error) {
if filepath.Separator != '/' && strings.ContainsRune(name, filepath.Separator) ||
strings.Contains(name, "\x00") {
return "", errInvalidFilePathCharacter
}
dir := string(d)
if dir == "" {
dir = "."
}
return filepath.Join(dir, filepath.FromSlash(path.Clean("/"+name))), nil
}