ip_white.go 623 B

1234567891011121314151617181920212223242526272829303132
  1. package middleware
  2. import (
  3. "app/commons/core"
  4. "github.com/gin-gonic/gin"
  5. "net/http"
  6. )
  7. // IPWhitelist 创建一个 IP 白名单中间件
  8. func IPWhitelist(allowedIPs []string) gin.HandlerFunc {
  9. return func(c *gin.Context) {
  10. clientIP := c.ClientIP()
  11. remoteIp := c.RemoteIP()
  12. core.JobLog.Infof("IPWhitelist:%s remoteIp:%s", clientIP, remoteIp)
  13. allowed := false
  14. for _, ip := range allowedIPs {
  15. if ip == clientIP || ip == remoteIp {
  16. allowed = true
  17. break
  18. }
  19. }
  20. if !allowed {
  21. c.AbortWithStatusJSON(http.StatusForbidden, gin.H{
  22. "error": "Access denied",
  23. })
  24. return
  25. }
  26. c.Next()
  27. }
  28. }