重写
Rewrite 中间件会根据提供的规则重写 URL 路径。它有助于保持向后兼容,或创建更简洁、 更具描述性的链接。
所有核心中间件都位于 middleware 包中:
import "github.com/labstack/echo/v5/middleware"e.Pre(middleware.Rewrite(map[string]string{ "/old": "/new", "/api/*": "/$1", "/js/*": "/public/javascripts/$1", "/users/*/orders/*": "/user/$1/order/$2",}))星号捕获的值可以按索引获取,例如 $1、$2 等。每个星号都是非贪婪的
(转换为捕获组 (.*?));使用多个星号时,尾随 * 会匹配路径剩余部分。
e := echo.New()e.Pre(middleware.RewriteWithConfig(middleware.RewriteConfig{}))RewriteConfig · github.com/labstack/echo/v5@5196b9b
字段说明由英文源码注释生成。
| 字段 | 类型 | 说明 | 源码 |
|---|---|---|---|
Skipper | Skipper | Skipper defines a function to skip middleware. | L17 |
Rules | map[string]string | Rules defines the URL path rewrite rules. The values captured in asterisk can be retrieved by index e.g. $1, $2 and so on. Example: "/old": "/new", "/api/*": "/$1", "/js/*": "/public/javascripts/$1", "/users/*/orders/*": "/user/$1/order/$2", Required. | L27 |
RegexRules | map[*regexp.Regexp]string | RegexRules defines the URL path rewrite rules using regexp.Rexexp with captures Every capture group in the values can be retrieved by index e.g. $1, $2 and so on. Example: "^/old/[0.9]+/": "/new", "^/api/.+?/(.*)": "/v2/$1", | L34 |
默认配置:
| 名称 | 值 |
|---|---|
| Skipper | DefaultSkipper |
基于正则表达式的规则
Section titled “基于正则表达式的规则”对于路径的高级重写,也可以使用正则表达式定义规则。可以用 () 定义普通捕获组,
并在重写后的路径中按索引引用($1、$2 等)。
RegexRules 可以和普通 Rules 组合使用。
e.Pre(middleware.RewriteWithConfig(middleware.RewriteConfig{ Rules: map[string]string{ "^/v1/*": "/v2/$1", }, RegexRules: map[*regexp.Regexp]string{ regexp.MustCompile("^/foo/([0-9].*)"): "/num/$1", regexp.MustCompile("^/bar/(.+?)/(.*)"): "/baz/$2/$1", },}))