gofiber / fiber

⚡️ Express inspired web framework written in Go
https://gofiber.io
MIT License
33.77k stars 1.66k forks source link

🐛 [Bug]: Static server in sub app does not work #3104

Open lephattan opened 2 months ago

lephattan commented 2 months ago

Question Description

I am trying to set app a static server in a sub app, but it does not seem to work. The problem can be reproduced with the snippet below.

Project struture:

tree .
#.
#├── go.mod
#├── go.sum
#├── main.go
#└── public
#    └── test.txt

Tests:

cat public/test.txt
# test

curl http://127.0.0.1:3000/
# Hello, world!%

curl http://127.0.0.1:3000/public/test.txt
# test

curl http://127.0.0.1:3000/subApp
# Hello from subApp%

curl http://127.0.0.1:3000/subApp/public/test.txt
# Cannot GET /subApp/public/test.txt%

Code Snippet (optional)

package main

import (
    "github.com/gofiber/fiber/v2"
    "github.com/gofiber/fiber/v2/middleware/logger"
)

func main() {
    app := fiber.New()
    logger := logger.New()
    app.Use(logger)

    app.Static("/public", "./public")

    app.Get("/", func(c *fiber.Ctx) error {
        return c.SendString("Hello, world!")
    })

    subApp := fiber.New()
    subApp.Use(logger)

    subApp.Static("/public", "./public")

    subApp.Get("/", func(c *fiber.Ctx) error {
        return c.SendString("Hello from subApp")
    })

    app.Mount("/subApp", subApp)
    app.Listen(":3000")
}

Checklist:

welcome[bot] commented 2 months ago

Thanks for opening your first issue here! 🎉 Be sure to follow the issue template! If you need help or want to chat with us, join us on Discord https://gofiber.io/discord

ReneWerner87 commented 2 months ago

thx for sharing, which version do you use?

lephattan commented 2 months ago

@ReneWerner87 I am using fiber v2.52.5 with go 1.23.0

thx for sharing, which version do you use?

Skyenought commented 1 month ago

https://github.com/gofiber/fiber/blob/6e7411403adc3f82cb941b6a038566006ed6e270/router.go#L404 @ReneWerner87 I found that when using mount, although the expected path of fs.root is correct, the result of fasthttp ctx.Path is '/' and '/public', which causes the access path to change from public to public/public, which is the reason for this bug.

fs := &fasthttp.FS{
    Root:                 root,

https://github.com/valyala/fasthttp/blob/c3050516d957b5bf75b353683c50302e4f955c6b/fs.go#L1074

// expect: ctx.Path ="/" filepath = "E:\projects_go\server\public"
// fact: ctx.Path = "/public" filepath = "E:\projects_go\server\public\public" 
ff, err = h.openFSFile(filePath, mustCompress, fileEncoding)
yinheli commented 1 month ago

Same issue for me. So I submit a PR.