1 回答

TA貢獻1789條經(jīng)驗 獲得超8個贊
下面是一些簡單的限制控制代碼,將其用作具有所述服務(wù)的唯一標(biāo)識符(在本例中為 IP)和要等待的時間的 IF 調(diào)用。正如您通過代碼所看到的,您可以將秒更改為分鐘或毫秒。你最好使用像cloudflare這樣的服務(wù),但作為最后一個選項,把它放在你的API中,并在處理程序代碼周圍放置一個IF語句,你可以限制對連接的控制。這是為了保持簡單,我相信還有其他優(yōu)雅的解決方案出來,我的愚蠢嘗試可能會被嘲笑,但我相信有人會從中吸取教訓(xùn),如果它們有意義,改進建議也會包括在內(nèi)。
/******************************************************************************
* _ _ _ _ _ _ _
* | | | | | | | | | | /\ | | |
* | |_| |__ _ __ ___ | |_| |_| | ___ / \ | | | _____ __
* | __| '_ \| '__/ _ \| __| __| |/ _ \ / /\ \ | | |/ _ \ \ /\ / /
* | |_| | | | | | (_) | |_| |_| | __// ____ \| | | (_) \ V V /
* \__|_| |_|_| \___/ \__|\__|_|\___/_/ \_\_|_|\___/ \_/\_/
* ----------------------------------------------------------------------------
* This function will temp store the value in a map and then remove it, it will
* return true or false if the item is in the map, Now sets delay on second response
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
var throttle = make(map[string]bool)
func throttleAllow(ip string, timeout int) (retVal bool) {
if throttle[ip] == true {
fmt.Println("WARM","-=Throttle=-To frequent calls from:",ip)
time.Sleep(time.Duration(timeout)*time.Second) //Random next cycle.
retVal = true // false will result is receiging to frequent message
} else {
throttle[ip] = true
go func(){
time.Sleep(time.Duration(timeout)*time.Second) //Random next cycle.
delete(throttle, ip)
}()
retVal = true
}
return
}
- 1 回答
- 0 關(guān)注
- 88 瀏覽
添加回答
舉報