domainValidator.go 862 B

12345678910111213141516171819202122232425262728293031
  1. // Package middleware provides HTTP middleware functions for the 3x-ui web panel,
  2. // including domain validation and URL redirection utilities.
  3. package middleware
  4. import (
  5. "net"
  6. "net/http"
  7. "strings"
  8. "github.com/gin-gonic/gin"
  9. )
  10. // DomainValidatorMiddleware returns a Gin middleware that validates the request domain.
  11. // It extracts the host from the request, strips any port number, and compares it
  12. // against the configured domain. Requests from unauthorized domains are rejected
  13. // with HTTP 403 Forbidden status.
  14. func DomainValidatorMiddleware(domain string) gin.HandlerFunc {
  15. return func(c *gin.Context) {
  16. host := c.Request.Host
  17. if colonIndex := strings.LastIndex(host, ":"); colonIndex != -1 {
  18. host, _, _ = net.SplitHostPort(c.Request.Host)
  19. }
  20. if host != domain {
  21. c.AbortWithStatus(http.StatusForbidden)
  22. return
  23. }
  24. c.Next()
  25. }
  26. }