跳转到内容

Static

Static 中间件从根目录提供文件。下面的示例在 / 提供 public/index.html。

在 echox 源码目录运行 cd reference/static && go run .,然后打开 http://localhost:1323/。

static/main.go
// SPDX-License-Identifier: MIT
// This complete example is the source for the Static middleware documentation.
package main
import (
"github.com/labstack/echo/v5"
"github.com/labstack/echo/v5/middleware"
)
func main() {
e := echo.New()
e.Use(middleware.StaticWithConfig(middleware.StaticConfig{
Root: "public",
EnablePathUnescaping: false, // Keep encoded slashes encoded when route guards protect files.
}))
if err := e.Start(":1323"); err != nil {
e.Logger.Error("server stopped", "error", err)
}
}

本页直接导入文档 CI 编译的同一个文件。示例将 EnablePathUnescaping 保持为 false,这是处理编码斜杠的安全默认值。

Root 指定要提供的目录。Browse 启用目录列表,HTML5 将未找到的路径转到索引文件,Filesystem 可接收 fs.FS。如果分组的 URL 前缀不应成为文件路径的一部分,请使用 IgnoreBase。

Echo v5.4.0 的 HTML5 模式仅对路由器返回的 404 提供索引文件。已匹配路由自身返回的 404 会原样返回;这对共用服务器的 SPA 和 API 很重要。

将 Static 中间件附加到非根路径的分组时,Echo 通常会将分组的 URL 前缀加入文件路径。如果文件系统根目录已经包含该前缀,请设置 IgnoreBase: true。分组需要有匹配的路由才能运行其中间件。

要提供嵌入式文件系统,请将 embed.FS 赋给 Filesystem,并将其中的资源目录设为 Root。完整程序见嵌入资源示例。

下表由所标注 Echo 修订版本的导出字段生成。它标记弃用字段,但不推断默认值或安全行为。

StaticConfig · github.com/labstack/echo/v5@5196b9b

字段说明由英文源码注释生成。

包源码中的字段
字段类型说明源码
Skipper Skipper Skipper defines a function to skip middleware. L26
Root string Root directory from where the static content is served (relative to given Filesystem). `Root: "."` means root folder from Filesystem. Required. L31
Filesystem fs.FS Filesystem provides access to the static content. Optional. Defaults to echo.Filesystem (serves files from `.` folder where executable is started) L35
Index string Index file for serving a directory. Optional. Default value "index.html". L39
HTML5 bool Enable HTML5 mode by forwarding all not-found requests to root so that SPA (single-page application) can handle the routing. Optional. Default value false. L44
Browse bool Enable directory browsing. Optional. Default value false. L48
IgnoreBase bool Enable ignoring of the base of the URL path. Example: when assigning a static middleware to a non root path group, the filesystem path is not doubled Optional. Default value false. L54
DisablePathUnescaping已弃用 bool Deprecated: this field is ignored, use EnablePathUnescaping instead. DisablePathUnescaping will be removed in a future version. Note: previously the zero value (false) enabled unescaping, which was the unsafe default. L58
EnablePathUnescaping bool EnablePathUnescaping enables unescaping of the request path (or of the wildcard param `*` when the middleware is used on a wildcard route) before the file is looked up. Default false (safe): the path is used in the same form as the router matched it, so encoded characters such as encoded slashes (%2f) are NOT decoded, preventing ACL bypass where /admin%2fprivate.txt bypasses a /admin/* route guard by not matching that route but being decoded to admin/private.txt. As a consequence, file names that the client sends with non-default escaping (e.g. `%2C`, `%40` or lowercase hex like `%c3%a9`) are not found. Set to true only when serving files whose names need such unescaping and you are not relying on route-based ACL guards to restrict access. Paths with ".", ".." or empty segments are never served, also after unescaping. Enabling echo.RouterConfig.UseEscapedPathForMatching makes this field irrelevant and can lead to security issues when using different Routes to exclude some of the files from being served. e.g. if you serve files from directory as such and use different route to exclude some of the files from being served. 0. given folder structure: public/ public/index.html public/admin/private.txt 1. share `public/` folder contents from the server root with `e.Static("/", "public")` 2. naively assume that everything under /admin folder is now forbidden e.GET("/admin/*", func(c *Context) error { return echo.ErrForbidden }) Then request to `/assets/../admin%2fprivate.txt` will be served as router does not match it to guarded route. L80
DirectoryListTemplate string DirectoryListTemplate is template to list directory contents Optional. Default to `directoryListHTMLTemplate` constant below. L84
包源码中的函数
类型源码
func Static(root string) echo.MiddlewareFunc L170
func StaticWithConfig(config StaticConfig) echo.MiddlewareFunc L177

Index 默认为 index.html。EnablePathUnescaping 默认为 false,因此通配符路径中的编码斜杠不会被解码。DisablePathUnescaping 已弃用,当前 Echo 会忽略它;确实需要解码时请使用 EnablePathUnescaping。

只有在文件名需要 URL 编码字符,且路由规则不限制子目录访问时才启用解码。在路由匹配后解码斜杠可能绕过保护性路由。

默认情况下,Static 根据路由器匹配时使用的路径形式查找文件。非默认转义的文件名(如 %2C、%40 或小写十六进制)需要 EnablePathUnescaping。包含 .、.. 或空段的路径(如 /assets//app.js)返回 404;HTML5 模式仍可返回索引文件。启用路径解码也会解码编码斜杠,因此不要与基于子目录路由的访问控制一起使用。e.Use(middleware.Static(...)) 先于路由和分组中间件运行;路由保护无法保护其文件。请将受保护文件放在根目录外,或通过带保护的 Echo#Static 提供。