Gin 中间件(ip访问黑名单,白名单)

package main

import (
    "github.com/gin-gonic/gin"
)

// IP 访问白名单
func IPWhiteListMiddleware() gin.HandlerFunc {
    return func(c *gin.Context) {
        ipList := []string{
            "127.0.0.1",
        }
        flag := false
        clientIp := c.ClientIP()
        for _, host := range ipList{
            if clientIp == host {
                flag = true
            }
        }
        if !flag {
            c.String(401, "%s, 不在白名单中拒绝访问 \n", clientIp)
            c.Abort()
        }
    }
}
// IP 访问黑名单
func IPBlackListMiddleware() gin.HandlerFunc {
    return func(c *gin.Context) {
        ipList := []string{
            "127.0.0.1",
        }
        flag := false
        clientIp := c.ClientIP()
        for _, host := range ipList{
            if clientIp == host {
                flag = true
            }
        }
        if flag {
            c.String(401, "%s, 在黑名单中,拒绝访问 \n", clientIp)
            c.Abort()
        }
    }
}

func main() {
    r := gin.Default()

    // 自定义中间件
    // r.Use(IPWhiteListMiddleware())
    r.Use(IPBlackListMiddleware())
    r.GET("/test", func(c *gin.Context) {
        c.String(200, "hello test")
    })

    r.Run()
}
讨论数量: 0

请勿发布不友善或者负能量的内容。与人为善,比聪明更重要!