当使用`http.ResponseBody`时,测量上传速度。

huangapple go评论76阅读模式
英文:

Measure upload speed when using http.ResponseBody

问题

在使用http.ResponseWriter上传大量数据时,有没有办法测量客户端的下载速度?

更新上下文:我正在为存储在块中的Blob存储编写流式下载端点。文件非常大,因此加载和缓冲整个Blob是不可行的。能够监视缓冲区状态、已写入的字节数或类似信息将允许更好地安排块下载。

例如,在向响应进行Write()操作时,有没有办法检查已排队的数据量?

以下是一个示例上下文,但不使用文件对象。

func downloadHandler(w http.ResponseWriter, req *http.Request, ps httprouter.Params) {
    // 打开某个文件。
    f := os.Open("somefile.txt")

    // 根据客户端的下载速度调整此循环的迭代速度。
    for {
        data := make([]byte, 1000)
        count, err := f.Read(data)
        if err != nil {
            log.Fatal(err)
        }
        if count == 0 {
            break
        }
        // 将数据块上传到客户端。
        w.Write(data[:count])
    }
}
英文:

Is there a way to measure a client's download speed when uploading a large quantity of data using an http.ResponseWriter?

Update for context: I'm writing a streaming download endpoint for blob storage which stores blobs in chunks. The files are very large, so loading and buffering whole blobs is not feasible. Being able to monitor the buffer state, bytes written or similar would allow better scheduling of the chunk downloads.

E.g. when Write()ing to the response, is there a way to check how much data is already queued?

An example of the context, but not using a file object.

func downloadHandler(w http.ResponseWriter, req *http.Request, ps httprouter.Params) {
	// Open some file.
	f := os.Open("somefile.txt")

	// Adjust the iteration speed of this loop to the client's download speed.
	for
	{ 
	    data := make([]byte, 1000)
	    count, err := f.Read(data)
	    if err != nil {
			log.Fatal(err)
	    }
	    if count == 0 {
			break
	    }
	   // Upload data chunk to client.
	   w.Write(data[:count])
	}
}

答案1

得分: 3

你可以实现一个自定义的http.ResponseWriter,用于测量发送的字节数并计算吞吐量。

可能已经有类似功能的包存在。谷歌找到了这个(我没有使用过)。

英文:

You could implement a custom http.ResponseWriter that measures bytes sent, and calculates throughput.

There are likely packages to do similar things already. Google found this one (which I haven't used).

huangapple
  • 本文由 发表于 2017年4月25日 18:34:37
  • 转载请务必保留本文链接:https://go.coder-hub.com/43608294.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定