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
|
package files
import (
"io/fs"
"path/filepath"
"strings"
"go.alanpearce.eu/website/internal/storage"
"go.alanpearce.eu/x/log"
"gitlab.com/tozd/go/errors"
)
type Reader struct {
root string
log *log.Logger
files map[string]*storage.File
}
func NewReader(path string, log *log.Logger) (*Reader, error) {
r := &Reader{
root: path,
log: log,
files: make(map[string]*storage.File),
}
if err := r.registerContentFiles(); err != nil {
return nil, errors.WithMessagef(err, "registering content files")
}
return r, nil
}
func (r *Reader) registerFile(urlpath string, filepath string) error {
file, err := r.OpenFile(urlpath, filepath)
if err != nil {
return errors.WithMessagef(err, "could not register file %s", filepath)
}
r.files[urlpath] = file
return nil
}
func (r *Reader) registerContentFiles() error {
err := filepath.WalkDir(r.root, func(filePath string, f fs.DirEntry, err error) error {
if err != nil {
return errors.WithMessagef(err, "failed to access path %s", filePath)
}
if f.IsDir() {
return nil
}
relPath, err := filepath.Rel(r.root, filePath)
if err != nil {
return errors.WithMessagef(err, "failed to make path relative, path: %s", filePath)
}
urlPath := fileNameToPathName("/" + relPath)
switch filepath.Ext(relPath) {
case ".br", ".gz":
return nil
}
return r.registerFile(urlPath, filePath)
})
if err != nil {
return errors.WithMessage(err, "could not walk directory")
}
return nil
}
func (r *Reader) GetFile(urlPath string) (*storage.File, error) {
return r.files[urlPath], nil
}
func (r *Reader) CanonicalisePath(path string) (cPath string, differs bool) {
cPath = path
if strings.HasSuffix(path, "/index.html") {
cPath, differs = strings.CutSuffix(path, "index.html")
} else if !strings.HasSuffix(path, "/") && r.files[path+"/"] != nil {
cPath, differs = path+"/", true
}
return cPath, differs
}
|