gin/middleware/ip_validate.go

66 lines
1.5 KiB
Go
Raw Normal View History

2022-06-25 23:37:10 +08:00
// Package middleware ...
//
// Description : middleware ...
//
// Author : go_developer@163.com<白茶清欢>
//
// Date : 2022-06-25 23:24
package middleware
import (
"git.zhangdeman.cn/zhangdeman/gin/define"
"git.zhangdeman.cn/zhangdeman/gin/response"
2023-08-10 14:47:20 +08:00
networkUtil "git.zhangdeman.cn/zhangdeman/network/util"
2022-06-25 23:37:10 +08:00
"github.com/gin-gonic/gin"
)
// ValidateBlackIPMiddleware 验证黑名单IP的中间件
//
// Author : go_developer@163.com<白茶清欢>
//
// Date : 23:24 2022/6/25
func ValidateBlackIPMiddleware(code interface{}, httpCode int, validateFunc define.IsBlackIP) gin.HandlerFunc {
return func(ctx *gin.Context) {
if nil == validateFunc {
// 不验证黑名单
ctx.Next()
return
}
2024-09-24 15:05:02 +08:00
remoteIp := networkUtil.IP.GetRemoteIP(ctx.Request)
if validateFunc(ctx, remoteIp) {
2022-06-25 23:37:10 +08:00
// 命中黑名单
2024-09-24 15:05:02 +08:00
response.Send(ctx, code, httpCode, map[string]any{
"remote_ip": remoteIp,
}, nil)
2022-06-25 23:37:10 +08:00
ctx.Abort()
return
}
ctx.Next()
}
}
// ValidateWhiteIPMiddleware 是否白名单IP
//
// Author : go_developer@163.com<白茶清欢>
//
// Date : 23:33 2022/6/25
func ValidateWhiteIPMiddleware(code interface{}, httpCode int, validateFunc define.IsWhiteIP) gin.HandlerFunc {
return func(ctx *gin.Context) {
if nil == validateFunc {
// 不验证白名单
ctx.Next()
return
}
2024-09-24 15:05:02 +08:00
remoteIp := networkUtil.IP.GetRemoteIP(ctx.Request)
if !validateFunc(ctx, remoteIp) {
2022-06-25 23:37:10 +08:00
// 非名单
2024-09-24 15:05:02 +08:00
response.Send(ctx, code, httpCode, map[string]any{
"remote_ip": remoteIp,
}, nil)
2022-06-25 23:37:10 +08:00
ctx.Abort()
return
}
ctx.Next()
}
}