增加黑白名单验证的中间件
This commit is contained in:
parent
754a8762ee
commit
5b4fb6802a
24
define/middleare.go
Normal file
24
define/middleare.go
Normal file
@ -0,0 +1,24 @@
|
||||
// Package define ...
|
||||
//
|
||||
// Description : define ...
|
||||
//
|
||||
// Author : go_developer@163.com<白茶清欢>
|
||||
//
|
||||
// Date : 2022-06-25 23:25
|
||||
package define
|
||||
|
||||
import "github.com/gin-gonic/gin"
|
||||
|
||||
// IsBlackIP 是否是黑名单IP
|
||||
//
|
||||
// Author : go_developer@163.com<白茶清欢>
|
||||
//
|
||||
// Date : 23:25 2022/6/25
|
||||
type IsBlackIP func(ctx *gin.Context, clientIP string) bool
|
||||
|
||||
// IsWhiteIP 是否白名单IP
|
||||
//
|
||||
// Author : go_developer@163.com<白茶清欢>
|
||||
//
|
||||
// Date : 23:27 2022/6/25
|
||||
type IsWhiteIP func(ctx *gin.Context, clientIP string) bool
|
@ -30,6 +30,7 @@ func InitRequest() gin.HandlerFunc {
|
||||
ctx.Set(define.TraceIDField, traceID)
|
||||
ctx.Set(define.RequestIDField, requestID)
|
||||
ctx.Set(define.StartRequestTimeField, time.Now().UnixNano())
|
||||
ctx.Next()
|
||||
}
|
||||
}
|
||||
|
||||
|
59
middleware/ip_validate.go
Normal file
59
middleware/ip_validate.go
Normal file
@ -0,0 +1,59 @@
|
||||
// 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"
|
||||
"git.zhangdeman.cn/zhangdeman/util"
|
||||
"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
|
||||
}
|
||||
if validateFunc(ctx, util.IP.GetRemoteIP(ctx.Request)) {
|
||||
// 命中黑名单
|
||||
response.Send(ctx, code, httpCode, nil)
|
||||
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
|
||||
}
|
||||
if !validateFunc(ctx, util.IP.GetRemoteIP(ctx.Request)) {
|
||||
// 非名单
|
||||
response.Send(ctx, code, httpCode, nil)
|
||||
ctx.Abort()
|
||||
return
|
||||
}
|
||||
ctx.Next()
|
||||
}
|
||||
}
|
Loading…
Reference in New Issue
Block a user