Pular para o conteúdo

Static

O middleware Static serve arquivos de um diretório raiz. O exemplo serve public/index.html em /.

No repositório do echox, execute cd reference/static && go run . e abra 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)
}
}

A página importa o mesmo arquivo compilado pela CI da documentação. O exemplo mantém EnablePathUnescaping em false, o padrão seguro para barras codificadas.

Root define o diretório servido. Browse habilita a listagem de diretórios, HTML5 encaminha caminhos não encontrados ao arquivo de índice e Filesystem aceita um fs.FS. Use IgnoreBase quando o prefixo da URL de um grupo não deve entrar no caminho do arquivo.

No Echo v5.4.0, HTML5 serve o arquivo de índice apenas para um 404 do roteador. Um 404 retornado por uma rota correspondente é preservado; isso importa quando uma SPA e uma API compartilham o servidor.

Em um grupo fora da raiz, o Echo normalmente inclui o prefixo da URL do grupo no caminho do arquivo. Use IgnoreBase: true se o diretório raiz já incluir esse prefixo. O grupo precisa de uma rota correspondente para executar seu middleware.

Para servir um sistema de arquivos incorporado, atribua seu embed.FS a Filesystem e o diretório dos recursos a Root. Veja o cookbook de recursos incorporados.

A tabela vem dos campos exportados da revisão indicada do Echo. Ela marca campos obsoletos, mas não infere padrões nem regras de segurança.

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

As descrições dos campos são geradas dos comentários do código-fonte em inglês.

Campos do código-fonte
CampoTipoDescriçãoCódigo
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
DisablePathUnescapingObsoleto 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
Funções do código-fonte
TipoCódigo
func Static(root string) echo.MiddlewareFunc L170
func StaticWithConfig(config StaticConfig) echo.MiddlewareFunc L177

Index usa index.html por padrão. EnablePathUnescaping é false por padrão: barras codificadas no caminho curinga continuam codificadas. DisablePathUnescaping está obsoleto e é ignorado; use EnablePathUnescaping quando precisar habilitar a decodificação.

Habilite-a somente se precisar de caracteres codificados em nomes de arquivos e se suas rotas não restringirem o acesso a subdiretórios. Decodificar uma barra após o roteamento pode contornar uma rota de proteção.

Atualização de segurança do Echo (v5.4.0 / v4.16.0)

Seção intitulada “Atualização de segurança do Echo (v5.4.0 / v4.16.0)”

Por padrão, Static resolve arquivos a partir da mesma forma de caminho usada pelo roteador. Nomes pedidos com escape não padrão (%2C, %40 ou hexadecimal minúsculo) exigem EnablePathUnescaping. Segmentos ., .. ou vazios (por exemplo /assets//app.js) retornam 404; HTML5 ainda pode servir o índice. Ativar a decodificação também decodifica barras codificadas: não combine isso com controle de acesso baseado em rotas. e.Use(middleware.Static(...)) executa antes dos middlewares de rota e grupo; suas proteções não cobrem esses arquivos. Mantenha arquivos protegidos fora da raiz ou sirva-os com Echo#Static atrás de uma proteção.