コンテンツにスキップ

リライト

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
パッケージのソースコードの関数
型ソース
func Rewrite(rules map[string]string) echo.MiddlewareFunc L40
func RewriteWithConfig(config RewriteConfig) echo.MiddlewareFunc L49

デフォルト設定:

名前値
SkipperDefaultSkipper

パスの高度な書き換えでは、正規表現でルールを定義することもできます。 通常のキャプチャグループは () で定義し、書き換え後のパスでインデックス ($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",
},
}))