2017-12-28 21:24:34 +02:00
|
|
|
package middleware
|
|
|
|
|
|
|
|
import (
|
2019-01-30 12:56:56 +02:00
|
|
|
"github.com/labstack/echo/v4"
|
2020-09-03 09:39:57 +02:00
|
|
|
"regexp"
|
2017-12-28 21:24:34 +02:00
|
|
|
)
|
|
|
|
|
|
|
|
type (
|
|
|
|
// RewriteConfig defines the config for Rewrite middleware.
|
|
|
|
RewriteConfig struct {
|
|
|
|
// Skipper defines a function to skip middleware.
|
|
|
|
Skipper Skipper
|
|
|
|
|
|
|
|
// Rules defines the URL path rewrite rules. The values captured in asterisk can be
|
|
|
|
// retrieved by index e.g. $1, $2 and so on.
|
2018-01-31 05:02:29 +02:00
|
|
|
// Example:
|
2017-12-28 21:24:34 +02:00
|
|
|
// "/old": "/new",
|
|
|
|
// "/api/*": "/$1",
|
|
|
|
// "/js/*": "/public/javascripts/$1",
|
|
|
|
// "/users/*/orders/*": "/user/$1/order/$2",
|
|
|
|
// Required.
|
|
|
|
Rules map[string]string `yaml:"rules"`
|
|
|
|
|
|
|
|
rulesRegex map[*regexp.Regexp]string
|
|
|
|
}
|
|
|
|
)
|
|
|
|
|
|
|
|
var (
|
|
|
|
// DefaultRewriteConfig is the default Rewrite middleware config.
|
|
|
|
DefaultRewriteConfig = RewriteConfig{
|
|
|
|
Skipper: DefaultSkipper,
|
|
|
|
}
|
|
|
|
)
|
|
|
|
|
|
|
|
// Rewrite returns a Rewrite middleware.
|
|
|
|
//
|
|
|
|
// Rewrite middleware rewrites the URL path based on the provided rules.
|
|
|
|
func Rewrite(rules map[string]string) echo.MiddlewareFunc {
|
|
|
|
c := DefaultRewriteConfig
|
|
|
|
c.Rules = rules
|
|
|
|
return RewriteWithConfig(c)
|
|
|
|
}
|
|
|
|
|
|
|
|
// RewriteWithConfig returns a Rewrite middleware with config.
|
|
|
|
// See: `Rewrite()`.
|
|
|
|
func RewriteWithConfig(config RewriteConfig) echo.MiddlewareFunc {
|
|
|
|
// Defaults
|
|
|
|
if config.Rules == nil {
|
|
|
|
panic("echo: rewrite middleware requires url path rewrite rules")
|
|
|
|
}
|
|
|
|
if config.Skipper == nil {
|
|
|
|
config.Skipper = DefaultBodyDumpConfig.Skipper
|
|
|
|
}
|
|
|
|
|
2020-09-03 09:39:57 +02:00
|
|
|
config.rulesRegex = rewriteRulesRegex(config.Rules)
|
2017-12-28 21:24:34 +02:00
|
|
|
|
|
|
|
return func(next echo.HandlerFunc) echo.HandlerFunc {
|
|
|
|
return func(c echo.Context) (err error) {
|
|
|
|
if config.Skipper(c) {
|
|
|
|
return next(c)
|
|
|
|
}
|
|
|
|
|
|
|
|
req := c.Request()
|
2020-09-03 09:39:57 +02:00
|
|
|
// Set rewrite path and raw path
|
|
|
|
rewritePath(config.rulesRegex, req)
|
2018-01-30 20:27:57 +02:00
|
|
|
return next(c)
|
2017-12-28 21:24:34 +02:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|