Serving Static Files

File server

You can use http.FileServeropen in new window with BunRouter's concise API with the help of bunrouter.HTTPHandleropen in new window converter, for exampleopen in new window:

//go:embed files
var filesFS embed.FS

func main() {
	fileServer := http.FileServer(http.FS(filesFS))

	router := bunrouter.New(
		bunrouter.Use(reqlog.NewMiddleware(
			reqlog.FromEnv("BUNDEBUG"),
		)),
	)

	router.GET("/", indexHandler)
	router.GET("/files/*path", bunrouter.HTTPHandler(fileServer))
}

fs.Sub

If you want to serve files without a folder name, use fs.Subopen in new window:

//go:embed files
var filesFS embed.FS

func main() {
    // Retrieve files subtree.
	filesFS, err := fs.Sub(filesFS, "files")
	if err != nil {
		panic(err)
	}

	fileServer := http.FileServer(http.FS(filesFS))

	router := bunrouter.New(
		bunrouter.Use(reqlog.NewMiddleware(
			reqlog.FromEnv("BUNDEBUG"),
		)),
	)

	router.GET("/*path", bunrouter.HTTPHandler(fileServer))
}

http.StripPrefix

If you want to serve files under a different prefix, use http.StripPrefixopen in new window. In the following example we change /files prefix to /static/files prefix:

//go:embed files
var filesFS embed.FS

func main() {
	filesFS, err := fs.Sub(filesFS, "files")
	if err != nil {
		panic(err)
	}

	fileServer := http.FileServer(http.FS(filesFS))
	fileServer = http.StripPrefix("/static/files", fileServer)

	router := bunrouter.New(
		bunrouter.Use(reqlog.NewMiddleware(
			reqlog.FromEnv("BUNDEBUG"),
		)),
	)

	router.GET("/static/files/*path", bunrouter.HTTPHandler(fileServer))
}