我目前正在开发一个下载服务器。我需要将用户的下载速度限制为100KB/s。如何限制Go的下载速度?
这是我的代码:
func serveFile(w http.ResponseWriter, r *http.Request) {
fileID := r.URL.Query().Get("fileID")
if len(fileID) != 0 {
w.Header().Set("Content-Disposition", "attachment; filename=filename.txt")
w.Header().Set("Content-Type", r.Header.Get("Content-Type"))
w.Header().Set("Content-Length", r.Header.Get("Content-Length"))
file, err := os.Open(fmt.Sprintf("../../bin/files/test.txt"))
defer file.Close()
if err != nil {
http.NotFound(w, r)
return
}
io.Copy(w, file)
} else {
io.WriteString(w, "Invalid request.")
}
}
然后我发现了一个包在GitHub上,我的代码,成为了继:
func serveFile(w http.ResponseWriter, r *http.Request) {
fileID := r.URL.Query().Get("fileID")
if len(fileID) != 0 {
w.Header().Set("Content-Disposition", "attachment; filename=Wiki.png")
w.Header().Set("Content-Type", r.Header.Get("Content-Type"))
w.Header().Set("Content-Length", r.Header.Get("Content-Length"))
file, err := os.Open(fmt.Sprintf("../../bin/files/test.txt"))
defer file.Close()
if err != nil {
http.NotFound(w, r)
return
}
bucket := ratelimit.NewBucketWithRate(100*1024, 100*1024)
reader := bufio.NewReader(file)
io.Copy(w, ratelimit.Reader(reader, bucket))
} else {
io.WriteString(w, "Invalid request.")
}
}
但我发现了这个错误:
Corrupted Content Error
The page you are trying to view cannot be shown because an error in the data transmission was detected.
这是我在Go游乐场的代码:http://play.golang.org/p/ulgXQl4eQO
我不知道那个包,但我限制了作家,而不是读者。此外,Content-Type和Content-Length标题不应该从请求中复制,而应由文件类型和文件长度来设置。此外,你正在阅读一个文本文件,并将其写为png。 – 2015-04-04 11:20:24
@Not_a_Golfer它是https://github.com/juju/ratelimit,虽然我更喜欢https://github.com/aybabtme/iocontrol – VonC 2015-04-04 11:43:53