2023-05-30 20:43:46 +00:00
|
|
|
package middleware
|
|
|
|
|
|
|
|
|
|
import (
|
|
|
|
|
"net/http"
|
|
|
|
|
"strings"
|
|
|
|
|
|
|
|
|
|
"github.com/gin-gonic/gin"
|
|
|
|
|
)
|
|
|
|
|
|
2025-09-20 07:35:50 +00:00
|
|
|
// RedirectMiddleware returns a Gin middleware that handles URL redirections.
|
|
|
|
|
// It provides backward compatibility by redirecting old '/xui' paths to new '/panel' paths,
|
|
|
|
|
// including API endpoints. The middleware performs permanent redirects (301) for SEO purposes.
|
2023-05-30 20:43:46 +00:00
|
|
|
func RedirectMiddleware(basePath string) gin.HandlerFunc {
|
2026-04-03 00:44:51 +00:00
|
|
|
// Use a slice to guarantee longest-prefix-first matching order.
|
|
|
|
|
// A map would have nondeterministic iteration, causing "/xui/API" to
|
|
|
|
|
// sometimes match the shorter "/xui" rule instead.
|
|
|
|
|
redirects := []struct{ from, to string }{
|
|
|
|
|
{"panel/API", "panel/api"},
|
|
|
|
|
{"xui/API", "panel/api"},
|
|
|
|
|
{"xui", "panel"},
|
|
|
|
|
}
|
2023-05-30 20:43:46 +00:00
|
|
|
|
2026-04-03 00:44:51 +00:00
|
|
|
return func(c *gin.Context) {
|
2023-05-30 20:43:46 +00:00
|
|
|
path := c.Request.URL.Path
|
2026-04-03 00:44:51 +00:00
|
|
|
for _, r := range redirects {
|
|
|
|
|
from := basePath + r.from
|
|
|
|
|
to := basePath + r.to
|
2023-05-30 20:43:46 +00:00
|
|
|
|
|
|
|
|
if strings.HasPrefix(path, from) {
|
|
|
|
|
newPath := to + path[len(from):]
|
|
|
|
|
|
|
|
|
|
c.Redirect(http.StatusMovedPermanently, newPath)
|
|
|
|
|
c.Abort()
|
|
|
|
|
return
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
c.Next()
|
|
|
|
|
}
|
|
|
|
|
}
|