From 350a2657cd4733bcad92f57637da7b109499b8dc Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E7=99=BD=E8=8C=B6=E6=B8=85=E6=AC=A2?= Date: Wed, 28 Jul 2021 21:05:39 +0800 Subject: [PATCH] =?UTF-8?q?=E5=A2=9E=E5=8A=A0=E4=BA=86=E5=9F=BA=E4=BA=8EGI?= =?UTF-8?q?N=E7=9A=84=E9=BB=91=E7=99=BD=E5=90=8D=E5=8D=95=E5=88=A4?= =?UTF-8?q?=E6=96=AD=E6=9C=BA=E5=88=B6?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- gin/middleware/ip.go | 51 ++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 51 insertions(+) create mode 100644 gin/middleware/ip.go diff --git a/gin/middleware/ip.go b/gin/middleware/ip.go new file mode 100644 index 0000000..fe6012e --- /dev/null +++ b/gin/middleware/ip.go @@ -0,0 +1,51 @@ +// Package middleware ... +// +// Description : ip黑白名单的限制 +// +// Author : go_developer@163.com<白茶清欢> +// +// Date : 2021-07-29 5:52 下午 +package middleware + +import ( + "net/http" + + "github.com/gin-gonic/gin" +) + +// IPValidate IP和白名单的验证, 注意 : 既存在于白名单, 也存在于黑名单, 则认为是黑名单 +// +// Author : go_developer@163.com<白茶清欢> +// +// Date : 5:53 下午 2021/3/9 +func IPValidate(whiteIPList []string, blackIPList []string, responseData map[string]interface{}) gin.HandlerFunc { + return func(ctx *gin.Context) { + realClientIP := ctx.ClientIP() + if nil != blackIPList && len(blackIPList) > 0 { + for _, blackIP := range blackIPList { + if realClientIP == blackIP { + // 黑名单IP + ctx.AbortWithStatusJSON(http.StatusOK, responseData) + return + } + } + } + + if nil != whiteIPList && len(whiteIPList) > 0 { + isWhiteIP := false + for _, whiteIP := range whiteIPList { + if realClientIP == whiteIP { + isWhiteIP = true + break + } + } + if !isWhiteIP { + // 配置了白名单,但是非白名单IP + ctx.AbortWithStatusJSON(http.StatusOK, responseData) + return + } + } + + ctx.Next() + } +}