m_whitelist.go 1.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. package middleware
  2. import (
  3. "github.com/gin-gonic/gin"
  4. "net/http"
  5. )
  6. var (
  7. whitelistIP = map[string]bool{
  8. "192.168.1.100": true,
  9. "10.0.0.1": true,
  10. // 添加更多的白名单IP地址
  11. }
  12. whitelistRoutes = map[string]bool{
  13. "/yuexin-pay/swagger": true,
  14. // 添加更多的白名单路由
  15. }
  16. )
  17. // WhitelistMiddleware 白名单中间件
  18. func WhitelistMiddleware() gin.HandlerFunc {
  19. return func(c *gin.Context) {
  20. // 检查IP地址
  21. clientIP := c.ClientIP()
  22. if !isIPInWhitelist(clientIP) {
  23. c.JSON(http.StatusForbidden, gin.H{"error": "IP地址不在白名单中"})
  24. c.Abort()
  25. return
  26. }
  27. // 检查路由
  28. if !isRouteInWhitelist(c.FullPath()) {
  29. c.JSON(http.StatusForbidden, gin.H{"error": "路由不在白名单中"})
  30. c.Abort()
  31. return
  32. }
  33. c.Next()
  34. }
  35. }
  36. // isIPInWhitelist 检查IP地址是否在白名单中
  37. func isIPInWhitelist(ip string) bool {
  38. _, ok := whitelistIP[ip]
  39. return ok
  40. }
  41. // isRouteInWhitelist 检查路由是否在白名单中
  42. func isRouteInWhitelist(route string) bool {
  43. _, ok := whitelistRoutes[route]
  44. return ok
  45. }