V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
echooo0
V2EX  ›  程序员

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

  •  
  •   echooo0 · 2022-10-13 13:37:32 +08:00 · 1750 次点击
    这是一个创建于 532 天前的主题,其中的信息可能已经有所发展或是发生改变。

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

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

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

    5 条回复    2022-10-13 19:18:47 +08:00
    qi1070445109
        1
    qi1070445109  
       2022-10-13 14:12:16 +08:00 via Android
    没试过,但是不是可以调一下单位把数变小?
    echooo0
        2
    echooo0  
    OP
       2022-10-13 14:17:05 +08:00
    @qi1070445109 #1 你的意思是 time.Second 换其他单位嘛?
    danbai
        3
    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
        4
    Mohanson  
       2022-10-13 14:55:21 +08:00
    Rehtt
        5
    Rehtt  
       2022-10-13 19:18:47 +08:00 via Android
    还要考虑对 ip 限速,因为有多线程下载
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   1042 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 26ms · UTC 22:36 · PVG 06:36 · LAX 15:36 · JFK 18:36
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.