如何计算”net/http”客户端发送/接收的字节数?

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

How to count number of bytes sent/received by "net/http" Client?

问题

"net/http"Client.Do请求期间,是否有可能获取发送和接收的总字节数(用于监控或统计目的)?

如果不可能,如何以最小的开发工作量和性能影响获取这些信息?

英文:

Is it possible to get total number of bytes sent and received during "net/http" Client.Do request (for monitoring or statistical purposes)?

If not possible, how could you get this information with least development effort and performance impact?

答案1

得分: 1

对于发送的字节数,如果你使用client.Do,你应该能够在发送之前直接转储请求:

dump, err := httputil.DumpRequestOut(req, true)
if err != nil {
    log.Fatal(err)
}

fmt.Printf("request len:%d\n\n%q", len(dump), dump)

对于接收的字节数,你是指响应中的字节数吗?如果是的话,可以使用httputil.DumpResponse:

dump, err := httputil.DumpResponse(resp, true)
if err != nil {
    log.Fatal(err)
}

fmt.Printf("response len:%d\n\n%q", len(dump), dump)

这将获得字节数。从最小的影响来看,最后的影响将是通过循环遍历头部来分别测量正文和头部的字节数,因为这样你就不需要转储到字符串中,但这对你来说可能不会有很大的差别,所以我建议先尝试简单的方法。通过在golang.org文档上查看这两个函数的代码,你可以将其提取出来,并将累积字节替换为计数字节。

要跟踪执行过程,请查看httptrace包和client trace:

https://golang.org/pkg/net/http/httptrace/

如果你想调试连接,这是一个有用的工具。

英文:

For the number of bytes sent, you should be able to just dump the request before sending if you're using client.Do:

https://golang.org/pkg/net/http/httputil/#DumpRequestOut

dump, err := httputil.DumpRequestOut(req, true)
	if err != nil {
		log.Fatal(err)
	}

fmt.Printf("request len:%d\n\n%q",len(dump), dump) 

For the number of bytes received, do you mean the no of bytes in the response? If so use httputil.DumpResponse:

https://golang.org/pkg/net/http/httputil/#DumpResponse

dump, err := httputil.DumpResponse(resp, true)
if err != nil {
	log.Fatal(err)
}

fmt.Printf("response len:%d\n\n%q", len(dump),dump)

That will get you the counts, in terms of least impact, the last impact would be to measure body and headers separately by looping through headers, as then you won't be dumping to a string, but it's unlikely to make a huge difference to you so I'd try the simple way first. See the code for the two functions above by viewing src on golang.org docs, you could just pull that out and replace accumulating bytes with counting them.

For tracing execution, have a look at the httptrace package and client trace:

https://golang.org/pkg/net/http/httptrace/

if you want to debug connections this is a useful tool.

huangapple
  • 本文由 发表于 2017年3月3日 13:03:45
  • 转载请务必保留本文链接:https://go.coder-hub.com/42571049.html
匿名

发表评论

匿名网友

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

确定