Skip to content

Commit

Permalink
🩹 Fix: static server in sub app with mount (#3104)
Browse files Browse the repository at this point in the history
  • Loading branch information
yinheli committed Sep 14, 2024
1 parent 6e74114 commit fe948ca
Show file tree
Hide file tree
Showing 2 changed files with 39 additions and 1 deletion.
7 changes: 7 additions & 0 deletions router.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
package fiber

import (
"bytes"
"fmt"
"html"
"sort"
Expand Down Expand Up @@ -357,6 +358,12 @@ func (app *App) registerStatic(prefix, root string, config ...Static) {
IndexNames: []string{"index.html"},
PathRewrite: func(fctx *fasthttp.RequestCtx) []byte {
path := fctx.Path()
mountPath := app.MountPath()
if n := len(mountPath); n > 0 {
if bytes.Equal(path[:n], utils.UnsafeBytes(mountPath)) {
path = path[n:]
}
}
if len(path) >= prefixLen {
if isStar && app.getString(path[0:prefixLen]) == prefix {
path = append(path[0:0], '/')
Expand Down
33 changes: 32 additions & 1 deletion router_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -354,7 +354,7 @@ func Test_Router_Handler_Catch_Error(t *testing.T) {
func Test_Route_Static_Root(t *testing.T) {
t.Parallel()

dir := "./.github/testdata/fs/css"
dir := "./.github/testdata/fs/css" //nolint:goconst
app := New()
app.Static("/", dir, Static{
Browse: true,
Expand Down Expand Up @@ -471,6 +471,37 @@ func Test_Route_Static_HasPrefix(t *testing.T) {
body, err = io.ReadAll(resp.Body)
utils.AssertEqual(t, nil, err, "app.Test(req)")
utils.AssertEqual(t, true, strings.Contains(app.getString(body), "color"))

app = New()
app.Static("/css", dir)

resp, err = app.Test(httptest.NewRequest(MethodGet, "/css/style.css", nil))
utils.AssertEqual(t, nil, err, "app.Test(req)")
utils.AssertEqual(t, 200, resp.StatusCode, "Status code")

body, err = io.ReadAll(resp.Body)
utils.AssertEqual(t, nil, err, "app.Test(req)")
utils.AssertEqual(t, true, strings.Contains(app.getString(body), "color"))
}

func Test_Route_Static_SubApp(t *testing.T) {
t.Parallel()

dir := "./.github/testdata/fs/css"
app := New()

subApp := New()
subApp.Static("/css", dir)

app.Mount("/sub", subApp)

resp, err := app.Test(httptest.NewRequest(MethodGet, "/sub/css/style.css", nil))
utils.AssertEqual(t, nil, err, "app.Test(req)")
utils.AssertEqual(t, 200, resp.StatusCode, "Status code")

body, err := io.ReadAll(resp.Body)
utils.AssertEqual(t, nil, err, "app.Test(req)")
utils.AssertEqual(t, true, strings.Contains(app.getString(body), "color"))
}

func Test_Router_NotFound(t *testing.T) {
Expand Down

0 comments on commit fe948ca

Please sign in to comment.