增加了基于GIN的黑白名单判断机制

This commit is contained in:
白茶清欢 2021-07-28 21:05:39 +08:00
parent 76ca91c2a9
commit 350a2657cd

51
gin/middleware/ip.go Normal file
View File

@ -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()
}
}