Skip to content

Commit 50c72ba

Browse files
committed
Refactor to handle different file-serving cases
1 parent 78406b1 commit 50c72ba

File tree

2 files changed

+14
-5
lines changed

2 files changed

+14
-5
lines changed

nextrouter/nextrouter.go

Lines changed: 10 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -8,10 +8,11 @@ import (
88
"github.com/go-chi/chi/v5"
99
)
1010

11-
func serve(fileSystem fs.FS, filePath string) http.HandlerFunc {
12-
return func(w http.ResponseWriter, r *http.Request) {
13-
fmt.Println("Requesting file: " + filePath)
14-
bytes, err := fs.ReadFile(fileSystem, filePath)
11+
func serveFile(router chi.Router, fileSystem fs.FS, fileName string) {
12+
13+
handler := func(w http.ResponseWriter, r *http.Request) {
14+
fmt.Println("Requesting file: " + fileName)
15+
bytes, err := fs.ReadFile(fileSystem, fileName)
1516

1617
if err != nil {
1718
http.Error(w, http.StatusText(404), 404)
@@ -22,6 +23,8 @@ func serve(fileSystem fs.FS, filePath string) http.HandlerFunc {
2223
http.Error(w, http.StatusText(404), 404)
2324
}
2425
}
26+
27+
router.Get("/"+fileName, handler)
2528
}
2629

2730
func buildRouter(rtr chi.Router, fileSystem fs.FS, name string) {
@@ -31,6 +34,7 @@ func buildRouter(rtr chi.Router, fileSystem fs.FS, name string) {
3134
return
3235
}
3336

37+
fmt.Println("Recursing: " + name)
3438
for _, file := range files {
3539
name := file.Name()
3640

@@ -44,7 +48,8 @@ func buildRouter(rtr chi.Router, fileSystem fs.FS, name string) {
4448
buildRouter(r, sub, name)
4549
})
4650
} else {
47-
rtr.Get("/"+name, serve(fileSystem, name))
51+
serveFile(rtr, fileSystem, name)
52+
4853
}
4954
}
5055
}

nextrouter/nextrouter_test.go

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -68,6 +68,10 @@ func TestNextRouter(t *testing.T) {
6868
require.NoError(t, err)
6969
defer res.Body.Close()
7070

71+
res, err = request(server, "/test/a/b/c.html")
72+
require.NoError(t, err)
73+
defer res.Body.Close()
74+
7175
body, err := io.ReadAll(res.Body)
7276
require.NoError(t, err)
7377
require.Equal(t, string(body), "test123")

0 commit comments

Comments
 (0)