52 lines
1.2 KiB
Go
52 lines
1.2 KiB
Go
// 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()
|
|
}
|
|
}
|