go - Go 中的简单油门控制
问题描述
如何创建一个简单的油门控制来阻止您的 API 接收到许多请求。或有效地受到 DDOS 攻击?因为有时您可能有一个前向 API 将所有连接传递给您的服务。如前所述,还有一些其他解决方案可以在实际连接中构建节流阀,但是将有效的简单解决方案过于复杂化,查看推荐的解决方案,他们几乎可以通过将 id 添加到地图来执行以下建议。对于仍在学习的人来说,这不是一个糟糕的选择,但由于 go 非常棒,您可以尝试简单的方法,然后在您开始更好地理解机制时改进为更好的解决方案。尽管这被标记为宣传某本书或其他东西,但这只是我帮助他人的尝试。如果那很糟糕,那么我会一直很糟糕。:D
解决方案
这是一些简单的油门控制代码,将其用作具有所述服务的唯一标识符的 IF 调用,在本例中为 IP,以及您要等待的时间。正如您从代码中看到的那样,您可以将秒更改为分钟或毫秒。并且您最好使用 cloudflare 之类的服务,但作为最后的选择,将其放在您的 API 中并在处理程序代码周围放置一个 IF 语句,您可以限制控制连接。这是为了保持简单,我相信他们还有其他优雅的解决方案,我的愚蠢尝试可能会被嘲笑,但我相信有人会从中吸取教训,如果它们有意义,也会包括改进建议。
/******************************************************************************
* _ _ _ _ _ _ _
* | | | | | | | | | | /\ | | |
* | |_| |__ _ __ ___ | |_| |_| | ___ / \ | | | _____ __
* | __| '_ \| '__/ _ \| __| __| |/ _ \ / /\ \ | | |/ _ \ \ /\ / /
* | |_| | | | | | (_) | |_| |_| | __// ____ \| | | (_) \ 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
}
推荐阅读
- hyperledger - 使用composer.sh重启网络再次使用时会出现连接错误?
- sql - Delphi:我的 SQL 查询没有返回任何结果有什么问题
- javascript - 错误:找不到模块“readline-sync”:Node.js
- julia - 访问字典中的值时出现 Julia 键错误
- python - 使用 Python 在 WebDriverWait 中放置 %s 的位置
- android - Recyclerview addOnScrollListener 问题
- sql-server - 如果数据不存在,则复制表中的行
- mysql - Docker 为烧瓶应用程序编写数据库 url 环境变量
- python - 套接字异常无法在 python 中重新连接到网络
- django - 如何序列化自定义查询集结果?