关于 golang 的下载文件限速功能

2022-10-13 13:37:32 +08:00
 echooo0

https://gitee.com/jameson512/wego/blob/master/util/ratelimit/ratelimit.go

这段代码中 Wait 方法里面, time.Duration(l.count)*time.Second ,

在传入的数据 count 大于 8G 的时候,int 64 会溢出,不知道有什么好的优化方案么

1778 次点击
所在节点    程序员
5 条回复
qi1070445109
2022-10-13 14:12:16 +08:00
没试过,但是不是可以调一下单位把数变小?
echooo0
2022-10-13 14:17:05 +08:00
@qi1070445109 #1 你的意思是 time.Second 换其他单位嘛?
danbai
2022-10-13 14:21:50 +08:00
```
func main() {
http.HandleFunc("/", getfile)
// 设置访问的路由
err := http.ListenAndServe(":9090", nil)
// 设置监听的端口
if err != nil {
log.Fatal("ListenAndServe: ", err)
}
}
func getfile(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Disposition", fmt.Sprintf("attachment;filename=%s", "test.file"))
limiter := rate.NewLimiter(1024*1024, 1024)
size := 0
for size < 1048576000 {
bytes := make([]byte, rand.Int31n(1024))
if limiter.AllowN(time.Now(), len(bytes)) {
_, _ = w.Write(bytes)
size += len(bytes)
}
}
}

```
go 有官方的限流库
"golang.org/x/time/rate" 可以拿来改写下
Mohanson
2022-10-13 14:55:21 +08:00
Rehtt
2022-10-13 19:18:47 +08:00
还要考虑对 ip 限速,因为有多线程下载

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/886615

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX