Skip to content

Commit 3406fea

Browse files
author
Sergio Andres Virviescas Santana
committed
Fix subrouter group when ServeFiles
1 parent c24d142 commit 3406fea

File tree

2 files changed

+33
-0
lines changed

2 files changed

+33
-0
lines changed

router.go

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -291,6 +291,16 @@ func (r *Router) ServeFiles(path string, rootPath string) {
291291
if len(path) < 10 || path[len(path)-10:] != "/*filepath" {
292292
panic("path must end with /*filepath in path '" + path + "'")
293293
}
294+
295+
if r.beginPath != "/" {
296+
path = r.beginPath + path
297+
}
298+
299+
if r.parent != nil {
300+
r.parent.ServeFiles(path, rootPath)
301+
return
302+
}
303+
294304
prefix := path[:len(path)-10]
295305

296306
fileHandler := fasthttp.FSHandler(rootPath, strings.Count(prefix, "/"))

router_test.go

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -370,6 +370,8 @@ func TestRouterGroup(t *testing.T) {
370370
barHit = true
371371
ctx.SetStatusCode(fasthttp.StatusOK)
372372
})
373+
r6.ServeFiles("/static/*filepath", "./")
374+
373375
s := &fasthttp.Server{
374376
Handler: r1.Handler,
375377
}
@@ -499,6 +501,27 @@ func TestRouterGroup(t *testing.T) {
499501
t.FailNow()
500502
}
501503

504+
// testing multiple sub-router group - r6 (grouped from r5) to serve files
505+
rw.r.WriteString("GET /moo/foo/foo/static/router.go HTTP/1.1\r\n\r\n")
506+
go func() {
507+
ch <- s.ServeConn(rw)
508+
}()
509+
select {
510+
case err := <-ch:
511+
if err != nil {
512+
t.Fatalf("return error %s", err)
513+
}
514+
case <-time.After(100 * time.Millisecond):
515+
t.Fatalf("timeout")
516+
}
517+
if err := resp.Read(br); err != nil {
518+
t.Fatalf("Unexpected error when reading response: %s", err)
519+
}
520+
if !(resp.Header.StatusCode() == fasthttp.StatusOK && barHit) {
521+
t.Errorf("Chained routing failed with subrouter grouping.")
522+
t.FailNow()
523+
}
524+
502525
rw.r.WriteString("POST /qax HTTP/1.1\r\n\r\n")
503526
go func() {
504527
ch <- s.ServeConn(rw)

0 commit comments

Comments
 (0)