Skip to content

Commit 771f39d

Browse files
committed
Add recursive router building
1 parent fadc0b6 commit 771f39d

File tree

1 file changed

+19
-13
lines changed

1 file changed

+19
-13
lines changed

nextrouter/nextrouter.go

Lines changed: 19 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -23,28 +23,34 @@ func serve(fileSystem fs.FS, filePath string) http.HandlerFunc {
2323
}
2424
}
2525

26-
func buildRouter(parentFileSystem fs.FS, path string) (chi.Router, error) {
27-
fileSystem, err := fs.Sub(parentFileSystem, path)
26+
func buildRouter(rtr chi.Router, fileSystem fs.FS, path string) {
27+
files, err := fs.ReadDir(fileSystem, ".")
2828
if err != nil {
29-
return nil, err
29+
// TODO(Bryan): Log
30+
return
3031
}
31-
files, err := fs.ReadDir(fileSystem, ".")
32-
rtr := chi.NewRouter()
32+
3333
rtr.Route("/", func(r chi.Router) {
3434
for _, file := range files {
3535
name := file.Name()
36-
rtr.Get("/"+name, serve(fileSystem, name))
36+
37+
if file.IsDir() {
38+
sub, err := fs.Sub(fileSystem, name)
39+
if err != nil {
40+
// TODO(Bryan): Log
41+
continue
42+
}
43+
buildRouter(r, sub, path+"/"+name)
44+
} else {
45+
rtr.Get("/"+name, serve(fileSystem, name))
46+
}
3747
}
3848
})
39-
return rtr, nil
4049
}
4150

4251
// Handler returns an HTTP handler for serving a next-based static site
4352
func Handler(fileSystem fs.FS) (http.Handler, error) {
44-
45-
router, err := buildRouter(fileSystem, ".")
46-
if err != nil {
47-
return nil, err
48-
}
49-
return router, nil
53+
rtr := chi.NewRouter()
54+
buildRouter(rtr, fileSystem, "")
55+
return rtr, nil
5056
}

0 commit comments

Comments
 (0)