redirect.go 897 B

12345678910111213141516171819202122232425262728293031323334353637
  1. package middleware
  2. import (
  3. "net/http"
  4. "strings"
  5. "github.com/gin-gonic/gin"
  6. )
  7. // RedirectMiddleware returns a Gin middleware that handles URL redirections.
  8. // It provides backward compatibility by redirecting old '/xui' paths to new '/panel' paths,
  9. // including API endpoints. The middleware performs permanent redirects (301) for SEO purposes.
  10. func RedirectMiddleware(basePath string) gin.HandlerFunc {
  11. return func(c *gin.Context) {
  12. // Redirect from old '/xui' path to '/panel'
  13. redirects := map[string]string{
  14. "panel/API": "panel/api",
  15. "xui/API": "panel/api",
  16. "xui": "panel",
  17. }
  18. path := c.Request.URL.Path
  19. for from, to := range redirects {
  20. from, to = basePath+from, basePath+to
  21. if strings.HasPrefix(path, from) {
  22. newPath := to + path[len(from):]
  23. c.Redirect(http.StatusMovedPermanently, newPath)
  24. c.Abort()
  25. return
  26. }
  27. }
  28. c.Next()
  29. }
  30. }