V2EX = way to explore
V2EX 是一个关于分享和探索的地方
Sign Up Now
For Existing Member  Sign In
• 请不要在回答技术问题时复制粘贴 AI 生成的内容
echooo0
V2EX  ›  程序员

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

  •  
  •   echooo0 · Oct 13, 2022 · 2414 views
    This topic created in 1297 days ago, the information mentioned may be changed or developed.

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

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

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

    5 replies    2022-10-13 19:18:47 +08:00
    qi1070445109
        1
    qi1070445109  
       Oct 13, 2022 via Android
    没试过,但是不是可以调一下单位把数变小?
    echooo0
        2
    echooo0  
    OP
       Oct 13, 2022
    @qi1070445109 #1 你的意思是 time.Second 换其他单位嘛?
    danbai
        3
    danbai  
    PRO
       Oct 13, 2022
    ```
    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  
       Oct 13, 2022
    Rehtt
        5
    Rehtt  
       Oct 13, 2022 via Android
    还要考虑对 ip 限速,因为有多线程下载
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   2512 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 36ms · UTC 03:00 · PVG 11:00 · LAX 20:00 · JFK 23:00
    ♥ Do have faith in what you're doing.