英文:
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).
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论