dongshi1880 2014-11-28 11:22
浏览 641
已采纳

在golang中如何限制服务器上载和下载的速度?

How would I limit upload and download speed from the server in golang?

I'm writing a golang server to allow users to upload and download files. And file is big, about 1GB bytes. I want to limit the upload and download speed to (for instance) 1MB/s (configurable of course).

below is my upload code:

func uploadFile(w http.ResponseWriter, r *http.Request) {
    file, _, err := r.FormFile("file")

    if err != nil {
        http.Error(w, err.Error(), 500)
        return
    }

    defer file.Close()

    os.MkdirAll(`e:\test`, os.ModePerm)
    out, err := os.Create(`e:\test\test.mpg`)
    if err != nil {
        http.Error(w, err.Error(), 500)
        return
    }

    defer out.Close()

    _, err = io.Copy(out, file)
    if err != nil {
        http.Error(w, err.Error(), 500)
    }
}
  • 写回答

2条回答 默认 最新

  • duanba2001 2014-11-28 13:51
    关注

    There's a token bucket algorithm that can be helpful to implement such the rate limit. I found an example implementation, which you can use: https://github.com/juju/ratelimit

    package main
    
    import (
        "bytes"
        "fmt"
        "io"
        "time"
    
        "github.com/juju/ratelimit"
    )
    
    func main() {
        // Source holding 1MB
        src := bytes.NewReader(make([]byte, 1024*1024))
        // Destination
        dst := &bytes.Buffer{}
    
        // Bucket adding 100KB every second, holding max 100KB
        bucket := ratelimit.NewBucketWithRate(100*1024, 100*1024)
    
        start := time.Now()
    
        // Copy source to destination, but wrap our reader with rate limited one
        io.Copy(dst, ratelimit.Reader(src, bucket))
    
        fmt.Printf("Copied %d bytes in %s
    ", dst.Len(), time.Since(start))
    }
    

    After running it, the output is:

    Copied 1048576 bytes in 9.239607694s
    

    You can use different bucket implementations to provide desired behaviour. In your code, after setting up right token bucket, you would call:

    _, err = io.Copy(out, ratelimit.Reader(file, bucket))
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 微信小程序协议怎么写
  • ¥15 c语言怎么用printf(“\b \b”)与getch()实现黑框里写入与删除?
  • ¥20 怎么用dlib库的算法识别小麦病虫害
  • ¥15 华为ensp模拟器中S5700交换机在配置过程中老是反复重启
  • ¥15 java写代码遇到问题,求帮助
  • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看