ip_limit.go 1.3 KB
Newer Older
E
V2.0.0  
eoLinker API Management 已提交
1 2 3
package middleware

import (
E
V2.0.3  
eoLinker API Management 已提交
4
	"goku-ce/goku"
E
V2.0.0  
eoLinker API Management 已提交
5 6 7 8 9
	"net/http"
	"strings"
)


E
V2.0.3  
eoLinker API Management 已提交
10
func IPLimit(g *goku.Context,res http.ResponseWriter, req *http.Request) (bool,string) {
E
V2.0.0  
eoLinker API Management 已提交
11 12 13
    remoteAddr := req.RemoteAddr
	remoteIP := InterceptIP(remoteAddr, ":")
	if !globalIPLimit(g,remoteIP){
E
V2.0.3  
eoLinker API Management 已提交
14 15 16
		return false,"[Global] Illegal IP"
	} else if globalIPLimit(g,remoteIP) && !strategyIPLimit(g,remoteIP) {
		return false,"[Strategy] Illegal IP"
E
V2.0.0  
eoLinker API Management 已提交
17 18 19 20
	}
	return true,""
}

E
V2.0.3  
eoLinker API Management 已提交
21 22 23
func globalIPLimit(g *goku.Context,remoteIP string) bool{
	if g.GatewayInfo.IPLimitType == "black"{
		for _,ip := range g.GatewayInfo.IPBlackList{
E
V2.0.0  
eoLinker API Management 已提交
24 25 26 27 28
			if ip == remoteIP {
				return false
			}
		}
		return true
E
V2.0.3  
eoLinker API Management 已提交
29 30
	} else if g.GatewayInfo.IPLimitType == "white" {
		for _,ip := range g.GatewayInfo.IPWhiteList{
E
V2.0.0  
eoLinker API Management 已提交
31 32 33 34 35 36 37 38 39
			if ip == remoteIP {
				return true
			}
		}
		return false
	}
	return true
}

E
V2.0.3  
eoLinker API Management 已提交
40 41 42
func strategyIPLimit(g *goku.Context,remoteIP string) bool {
	if g.StrategyInfo.IPLimitType == "black" {
		for _,ip := range g.StrategyInfo.IPBlackList{
E
V2.0.0  
eoLinker API Management 已提交
43 44 45 46 47
			if ip == remoteIP {
				return false
			}
		}
		return true
E
V2.0.3  
eoLinker API Management 已提交
48 49
	} else if g.StrategyInfo.IPLimitType == "white" {
		for _,ip := range g.StrategyInfo.IPWhiteList{
E
V2.0.0  
eoLinker API Management 已提交
50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66
			if ip == remoteIP {
				return true
			}
		}
		return false
	}
	return true
}

func InterceptIP(str, substr string) string {
	result := strings.Index(str, substr)
	var rs string
	if result > 7 {
		rs = str[:result]
	}
	return rs
}