首页 > 解决方案 > 有没有办法将新的 go embed 功能与 echo 一起使用?

问题描述

有没有办法将新的 go embed 功能与 echo 一起使用?我想从嵌入 go embed 的文件中提供带有 echo 静态中间件的文件。 https://tip.golang.org/pkg/embed/ https://echo.labstack.com/guide/static-files

标签: goecho

解决方案


此问题链接到Mark Wolfe 的要点,该要点演示了一种非常直接的方法。该方法的核心是:

// content holds our static web server content.
//go:embed static/*
var content embed.FS

var contentHandler = echo.WrapHandler(http.FileServer(http.FS(content)))
// The embedded files will all be in the '/static' folder so need to rewrite the request (could also do this with fs.Sub)
var contentRewrite = middleware.Rewrite(map[string]string{"/*": "/static/$1"})

func SetupRoutes(...) {
   e.GET("/*", contentHandler, contentRewrite)
}

推荐阅读