Fork me on GitHub

版权声明 本站原创文章 由 萌叔 发表
转载请注明 萌叔 | https://vearne.cc

1.引言

今天萌叔翻看Golang的request库go-resty/resty,看了请求trace Info的相关的细节。
程序如下:

package main

import (
    "fmt"
    "github.com/go-resty/resty/v2"
)

func main() {
    target := "https://vearne.cc/"
    client := resty.New()
    resp, err := client.R().
        EnableTrace().
        Get(target)

    if err != nil {
        fmt.Println("error:", err)
        return
    }
    fmt.Println(len(resp.String()), resp.StatusCode())
    // Explore trace info
    fmt.Println("Request Trace Info:")
    ti := resp.Request.TraceInfo()
    fmt.Println("  DNSLookup     :", ti.DNSLookup)
    fmt.Println("  ConnTime      :", ti.ConnTime)
    fmt.Println("  TCPConnTime   :", ti.TCPConnTime)
    fmt.Println("  TLSHandshake  :", ti.TLSHandshake)
    fmt.Println("  ServerTime    :", ti.ServerTime)
    fmt.Println("  ResponseTime  :", ti.ResponseTime)
    fmt.Println("  TotalTime     :", ti.TotalTime)
    fmt.Println("  IsConnReused  :", ti.IsConnReused)
    fmt.Println("  IsConnWasIdle :", ti.IsConnWasIdle)
    fmt.Println("  ConnIdleTime  :", ti.ConnIdleTime)
    fmt.Println("  RequestAttempt:", ti.RequestAttempt)
    fmt.Println("  RemoteAddr    :", ti.RemoteAddr.String())
}

输出:

Request Trace Info:
  DNSLookup     : 4.043875ms
  ConnTime      : 151.117584ms
  TCPConnTime   : 14.618292ms
  TLSHandshake  : 132.028458ms
  ServerTime    : 27.451833ms
  ResponseTime  : 1.292625ms
  TotalTime     : 179.669542ms
  IsConnReused  : false
  IsConnWasIdle : false
  ConnIdleTime  : 0s
  RequestAttempt: 1
  RemoteAddr    : 101.42.231.114:443

很难只从注释搞清楚它们之间的关系,萌叔阅读下代码,花了张图。分享给大家。

2.图表

有几个要注意的点

2.1 DNSLookup和TCPConnTime包含在ConnTime中。

程序从连接池拿出的连接,是已经完成TLS握手的。
具体代码参考
net/http/transport.go

getConn() -> queueForDial() -> dialConnFor() -> dialConn()
func (t *Transport) dialConn(ctx context.Context, cm connectMethod) (pconn *persistConn, err error) {
    ...
    if cm.scheme() == "https" && t.hasCustomTLSDialer() {
        // 针对https
    } else {
        // 针对http
    }
    ...
}

2.2 ServerTime表示的是 gotFirstResponseByte – gotConn

因此ServerTime包含

  • 1)发送请求的耗时
  • 2) 服务端处理请求耗时
  • 3)Response对应的第1个数据包在网络传输的时间

微信公众号

发表回复

您的电子邮箱地址不会被公开。 必填项已用*标注

此站点使用Akismet来减少垃圾评论。了解我们如何处理您的评论数据