-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathrouter.go
81 lines (62 loc) · 1.6 KB
/
router.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
package plain
import (
"os"
"path"
"strings"
)
const (
pagesDir = "pages"
staticDir = "public"
indexPageFileName = "index"
)
// function for reading files when building routes' list.
// also, it will skip files which returned `nil` for `data` when building routes
type ReadPageFileFunc = func(filepath string) (data []byte, err error)
type route struct {
filepath string
urlpath string
data []byte
}
func getRoutes(p string, wd string, readPageFile ReadPageFileFunc) ([]route, error) {
var routes []route
dir, err := os.ReadDir(p)
if err != nil {
return routes, err
}
for _, file := range dir {
filepath := path.Join(p, file.Name())
if file.IsDir() {
nestedRoutes, err := getRoutes(filepath, wd, readPageFile)
if err != nil {
return routes, err
}
routes = append(routes, nestedRoutes...)
continue
}
fileExt := path.Ext(filepath)
route := route{
filepath: filepath,
urlpath: filePathToUrl(wd, filepath, fileExt),
}
data, err := readPageFile(filepath)
if err != nil {
return nil, err
}
if data == nil {
continue
}
route.data = data
routes = append(routes, route)
}
return routes, nil
}
// removes 'index' part from filename, so need to check if file is directory before calling this function
func filePathToUrl(wd, filepath, ext string) string {
fileUrlPath := strings.ReplaceAll(filepath, ext, "")
wdWithPagesDir := path.Join(wd, pagesDir)
urlpath := strings.ReplaceAll(fileUrlPath, wdWithPagesDir, "")
if strings.HasSuffix(urlpath, "index") {
urlpath = strings.ReplaceAll(urlpath, "index", "")
}
return urlpath
}