跳转到内容

提供静态文件

Echo 可以从文件系统或嵌入式文件系统提供图片、JavaScript、CSS、PDF、字体等静态资源。

Echo 使用 os.DirFS(".") 作为默认文件系统,其根目录是当前工作目录。 要更改它,请设置 Echo#Filesystem 字段:

e := echo.New()
e.Filesystem = os.DirFS("assets")

参见 Static 中间件

Echo#Static(prefix, root string) 会注册一条路由,从给定根目录按路径前缀提供静态文件。

assets 下通过 /static/* 提供任意文件。对 /static/js/main.js 的请求会提供 assets/js/main.js

e := echo.New()
e.Static("/static", "assets")

assets 下通过 /* 提供任意文件。对 /js/main.js 的请求会提供 assets/js/main.js

e := echo.New()
e.Static("/", "assets")

静态文件可以从任何 fs.FS 提供,包括 embed.FS。使用 echo.MustSubFS, 使提供的文件以正确子目录为根;embed.FS 会把其子目录作为自己的条目包含进来。

//go:embed "assets/images"
var images embed.FS
func main() {
e := echo.New()
e.StaticFS("/images", echo.MustSubFS(images, "assets/images"))
sc := echo.StartConfig{Address: ":1323"}
if err := sc.Start(context.Background(), e); err != nil {
e.Logger.Error("failed to start server", "error", err)
}
}

Echo#File(path, file string) 会注册一条路由,用于提供单个静态文件。

public/index.html 提供索引页:

e.File("/", "public/index.html")

app/assets/favicon.ico 提供 favicon:

e := echo.New()
e.Filesystem = os.DirFS("/")
e.File("/favicon.ico", "app/assets/favicon.ico") // The file path must not have a leading slash.