Ir al contenido

Static

El middleware Static sirve archivos desde un directorio raíz. Este ejemplo sirve public/index.html en /.

Desde el repositorio de echox, ejecuta cd reference/static && go run . y abre 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)
}
}

La página importa el mismo archivo que compila la CI de documentación. El ejemplo mantiene EnablePathUnescaping en false, el valor seguro por defecto para las barras codificadas.

Root indica el directorio que se sirve. Browse permite listar directorios, HTML5 reenvía las rutas no encontradas al archivo índice y Filesystem acepta un fs.FS. Usa IgnoreBase cuando el prefijo URL de un grupo no debe formar parte de la ruta del archivo.

En Echo v5.4.0, HTML5 sirve el índice solo ante un 404 del enrutador. Un 404 devuelto por una ruta coincidente se conserva; esto importa cuando una SPA comparte servidor con una API.

En un grupo que no está en la raíz, Echo normalmente incluye el prefijo URL del grupo en la ruta del archivo. Usa IgnoreBase: true si el directorio raíz ya incluye ese prefijo. El grupo necesita una ruta coincidente para ejecutar su middleware.

Para servir un sistema de archivos embebido, asigna tu embed.FS a Filesystem y el directorio de recursos a Root. Consulta el ejemplo de recursos embebidos.

Esta tabla procede de los campos exportados de la revisión indicada de Echo. Marca los campos obsoletos, pero no deduce valores predeterminados ni reglas de seguridad.

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

Las descripciones de los campos se generan a partir de comentarios del código fuente en inglés.

Campos del código fuente
CampoTipoDescripciónFuente
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
Funciones del código fuente
TipoFuente
func Static(root string) echo.MiddlewareFunc L170
func StaticWithConfig(config StaticConfig) echo.MiddlewareFunc L177

Index usa index.html por defecto. EnablePathUnescaping es false por defecto: las barras codificadas en la ruta comodín permanecen codificadas. DisablePathUnescaping está obsoleto y se ignora; usa EnablePathUnescaping si necesitas habilitar la decodificación.

Habilítala solo si necesitas caracteres codificados en los nombres de archivo y tus rutas no restringen el acceso a subdirectorios. Decodificar una barra después del enrutamiento puede eludir una ruta de protección.

Actualización de seguridad de Echo (v5.4.0 / v4.16.0)

Sección titulada «Actualización de seguridad de Echo (v5.4.0 / v4.16.0)»

Por defecto, Static resuelve archivos desde la misma forma de ruta que usó el enrutador. Los nombres pedidos con codificación no estándar (%2C, %40 o hexadecimales en minúsculas) requieren EnablePathUnescaping. Los segmentos ., .. o vacíos (por ejemplo /assets//app.js) devuelven 404; HTML5 aún puede servir el índice. Al activar la decodificación también se decodifican las barras codificadas: no la combines con control de acceso basado en rutas. e.Use(middleware.Static(...)) se ejecuta antes que los middlewares de rutas y grupos; sus guardas no protegen esos archivos. Mantén los archivos protegidos fuera de su raíz o sírvelos mediante Echo#Static detrás de una guarda.