fiber: 🐛 Can't find index.html with PathPrefix?

Fiber version v2.14.0

Issue description Getting a 404 trying to browse to / mounting a React app using PathPrefix and Index

Code snippet

package main

import (
	"embed"
	"net/http"

	"github.com/gofiber/fiber/v2"
	"github.com/gofiber/fiber/v2/middleware/filesystem"
)

// Embed build directory
//go:embed ui/build/*
var embedDirReact embed.FS

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

	//serve basic api route returning data
	app.Get("/ping", func(c *fiber.Ctx) error {
		return c.SendString("Hello, World!")
	})

	//serve react app
	app.Use("/", filesystem.New(filesystem.Config{
		Root: http.FS(embedDirReact),
		PathPrefix: "ui/build",
		Index: "index.html",
	}))
	
	app.Listen(":3000")
}

Result: Cannot GET /

Browsing to http://localhost:3000/index.html directly works fine.

About this issue

  • Original URL
  • State: closed
  • Created 3 years ago
  • Comments: 16 (5 by maintainers)

Most upvoted comments

yes, i also found the errors, the filesytem middleware is not yet fully ready for embedded filesystems

these filesystems behave a little bit different, so the index file can not be found, if i have time today, i will try to provide a fix

Super janky, but it’s a work around:

//go:embed testdata/*
var testEmbedDirStatic embed.FS

// For wrapping embed.FS to suffix any trailing / directories
// with an index.html
type EmbedFS struct {
	f embed.FS
}

// append index.html to any 'directories' that are opened
func (embed *EmbedFS) Open(name string) (fs.File, error) {
	if strings.HasSuffix(name, "/") {
		name += "index.html"
	}
	return embed.f.Open(name)
}

// wrap the embed.FS in &EmbedFS{...} and pass that to http.FS
func Setup(...) {
	app.Use("/embed", New(Config{
		Root:       http.FS(&EmbedFS{testEmbedDirStatic}),
		PathPrefix: "testdata",
		Index:      "index.html",
	}))
}

I’m having a similar problem, what’s weird is:

//go:embed static/favicon.ico
var faviconFile embed.FS

//go:embed static/*
var embedDirStatic embed.FS

...
	app.Use("/", filesystem.New(filesystem.Config{
		Root:       http.FS(embedDirStatic),
		PathPrefix: "",
		Browse:     false,
		Index:      "static/index.html",
	}))

	app.Use(favicon.New(favicon.ConfigDefault))

Works just fine treating index.html as the index. But I can’t access GET /index.html, I have to access GET /static/index.html.

If I set PathPrefix to “static” or “static/” then it stops working, but I can access GET /index.html.

@ReneWerner87 sorry mate - i played around a ton with this and tried that just to see if it worked. Updated my config above to be the actual one I have (my fault), and it’s the same behavior.