问题描述
我如何限制golang中的服务器的上传和下载速度?
How would I limit upload and download speed from the server in golang?
我正在写一个golang服务器,允许用户上传和下载文件。文件大,约1GB字节。我想限制上传和下载速度(例如)1MB / s(当然可以配置)。
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).
下面是我的上传代码:
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)
}
}
推荐答案
有一个令牌桶算法可以帮助您实现这样的速度限制它。我发现了一个示例实现,您可以使用它: https://github.com/juju/ratelimit
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\n", dst.Len(), time.Since(start))
}
运行它后,输出为:
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))
这篇关于我如何从golang的服务器限制上传和下载速度?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!