dreamMyDream2014 2015-04-04 10:12
浏览 562
已采纳

如何使用Go限制下载速度?

I'm currently developing a download server in Go. I need to limit the download speed of users to 100KB/s.

This was my code:

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.")
    }
}

Then I found a package on github and my code became the following:

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.")
    }
}

But I'm getting this error:

Corrupted Content Error

The page you are trying to view cannot be shown because an error in the data transmission was detected.

Here's my code on the Go playground: http://play.golang.org/p/ulgXQl4eQO

  • 写回答

2条回答 默认 最新

  • duanbo19834 2015-04-04 15:06
    关注

    I'm not seeing the error, but I did notice some issues with the code. For this:

    w.Header().Set("Content-Type", r.Header.Get("Content-Type"))
    

    You should use the mime package's:

    func TypeByExtension(ext string) string
    

    To determine the content type. (if you end up with the empty string default to application/octet-stream)

    For:

    w.Header().Set("Content-Length", r.Header.Get("Content-Length"))
    

    You need to get the content length from the file itself. By using the request content length, for a GET this basically ends up as a no-op, but for a POST you're sending back the wrong length, which might explain the error you're seeing. After you open the file, do this:

    fi, err := file.Stat()
    if err != nil {
        http.Error(w, err.Error(), 500)
        return
    }
    w.Header().Set("Content-Length", fmt.Sprint(fi.Size()))
    

    One final thing, when you open the file, if there's an error, you don't need to close the file handle. Do it like this instead:

    file, err := os.Open(...)
    if err != nil {
        http.NotFound(w, r)
        return
    }
    defer file.Close()
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 R语言Rstudio突然无法启动
  • ¥15 关于#matlab#的问题:提取2个图像的变量作为另外一个图像像元的移动量,计算新的位置创建新的图像并提取第二个图像的变量到新的图像
  • ¥15 改算法,照着压缩包里边,参考其他代码封装的格式 写到main函数里
  • ¥15 用windows做服务的同志有吗
  • ¥60 求一个简单的网页(标签-安全|关键词-上传)
  • ¥35 lstm时间序列共享单车预测,loss值优化,参数优化算法
  • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值