Golang编写自定义IP限流中间件
warning:
这篇文章距离上次修改已过183天,其中的内容可能已经有所变动。
以下是一个简化的Golang中间件示例,用于限制通过API的IP请求频率。
package main
import (
"net/http"
"time"
)
type IpRateLimit struct {
// 存储IP请求记录的map
ipRateMap map[string]int
// 时间窗口,例如5秒
duration time.Duration
// 允许的最大请求数
limit int
}
// 中间件处理函数
func (l *IpRateLimit) ServeHTTP(w http.ResponseWriter, r *http.Request, next http.HandlerFunc) {
ip := r.RemoteAddr
if l.ipRateMap[ip] >= l.limit {
http.Error(w, "Too many requests", http.StatusTooManyRequests)
return
}
for k, v := range l.ipRateMap {
if time.Now().Sub(v) > l.duration {
delete(l.ipRateMap, k)
}
}
l.ipRateMap[ip] = time.Now()
next(w, r)
}
func main() {
// 初始化IP限流中间件
ipRateLimiter := &IpRateLimit{
ipRateMap: make(map[string]int),
duration: 5 * time.Second,
limit: 10,
}
http.Handle("/api", ipRateLimiter.ServeHTTP(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Write([]byte("Hello, World!"))
})))
http.ListenAndServe(":8080", nil)
}
这段代码创建了一个简单的IP请求频率限制器,它记录每个IP在过去5秒内的请求次数,并且如果请求超过设定的限制(例如10次/5秒),则中间件会返回一个429 Too Many Requests的HTTP状态码。这个示例提供了一个基本框架,可以根据实际需求进行扩展和优化。
评论已关闭