|
|
package middleware |
|
|
|
|
|
import ( |
|
|
"strings" |
|
|
|
|
|
"github.com/labstack/echo/v4" |
|
|
) |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
func StripPathPrefix() echo.MiddlewareFunc { |
|
|
return func(next echo.HandlerFunc) echo.HandlerFunc { |
|
|
return func(c echo.Context) error { |
|
|
prefixes := c.Request().Header.Values("X-Forwarded-Prefix") |
|
|
originalPath := c.Request().URL.Path |
|
|
|
|
|
for _, prefix := range prefixes { |
|
|
if prefix != "" { |
|
|
normalizedPrefix := prefix |
|
|
if !strings.HasSuffix(prefix, "/") { |
|
|
normalizedPrefix = prefix + "/" |
|
|
} |
|
|
|
|
|
if strings.HasPrefix(originalPath, normalizedPrefix) { |
|
|
|
|
|
newPath := originalPath[len(normalizedPrefix):] |
|
|
if newPath == "" { |
|
|
newPath = "/" |
|
|
} |
|
|
|
|
|
if !strings.HasPrefix(newPath, "/") { |
|
|
newPath = "/" + newPath |
|
|
} |
|
|
|
|
|
c.Request().URL.Path = newPath |
|
|
c.Request().URL.RawPath = "" |
|
|
|
|
|
if c.Request().URL.RawQuery != "" { |
|
|
c.Request().RequestURI = newPath + "?" + c.Request().URL.RawQuery |
|
|
} else { |
|
|
c.Request().RequestURI = newPath |
|
|
} |
|
|
|
|
|
c.Set("_original_path", originalPath) |
|
|
break |
|
|
} else if originalPath == prefix || originalPath == prefix+"/" { |
|
|
|
|
|
return c.Redirect(302, normalizedPrefix) |
|
|
} |
|
|
} |
|
|
} |
|
|
|
|
|
return next(c) |
|
|
} |
|
|
} |
|
|
} |
|
|
|