log / setup static path in go fiber using embedded file system

To be able use embedded file system to serve static file we can’t use app.Static instead we can use middleware app.Use

Here the example:

package main

import (
	"embed"
	"log"
	"net/http"

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

// Embed a single file
//
//go:embed index.html
var f embed.FS

// Embed a directory
//
//go:embed assets/*
var embedDirStatic embed.FS

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

	// Access file "image.png" under `assets/` directory via URL: `http://<server>/assets/image.png`.
	// Without `PathPrefix`, you have to access it via URL:
	// `http://<server>/assets/image.png`.
	app.Use("/assets", filesystem.New(filesystem.Config{
		Root:       http.FS(embedDirStatic),
		PathPrefix: "assets",
	}))

        // only expose the index.html
	app.Use("*", func(ctx *fiber.Ctx) error {
		return filesystem.SendFile(ctx, http.FS(f), "index.html")
	})

	log.Fatal(app.Listen(":3023"))
}

Source and detailed discussion: https://github.com/gofiber/fiber/issues/2526#issuecomment-1617637815

Written on 2024-01-11 03:20:00 +0700 Edited on 2024-03-11 03:50:00 +0700