一尘不染

在golang中获取TTFB(到第一个字节的时间)值

go

我正在尝试获取价值TTFB和连接价值

    c := exec.Command(
        "curl", "-w",
        "Connect: %{time_connect} TTFB: %{time_starttransfer} Total time: %{time_total}",
        "-o",
        "/dev/null",
        "http://my.domain/favicon.ico")

    cID, err := c.Run()
    fmt.Printf("%s", cID)

它会像

Connect: 0.205 TTFB: 0.353 Total time: 0.354

但是,我只需要TTFB , Connect, Total timegolang变量中value的值。

另外,有什么方法可以在不专门使用curl的情况下获取值?


阅读 261

收藏
2020-07-02

共1个答案

一尘不染

自Go 1.7起就有对此的内置支持。Go
1.7添加了HTTP跟踪,请阅读博客文章:HTTP跟踪简介

您可以指定在发出HTTP(S)请求时在适当的阶段/点调用的回调函数。您可以通过创建值来指定回调函数httptrace.ClientTrace,然后使用来“武装”它httptrace.WithClientTrace()

这是一个示例函数,该函数获取URL参数,并打印获取它的时间:

func timeGet(url string) {
    req, _ := http.NewRequest("GET", url, nil)

    var start, connect, dns, tlsHandshake time.Time

    trace := &httptrace.ClientTrace{
        DNSStart: func(dsi httptrace.DNSStartInfo) { dns = time.Now() },
        DNSDone: func(ddi httptrace.DNSDoneInfo) {
            fmt.Printf("DNS Done: %v\n", time.Since(dns))
        },

        TLSHandshakeStart: func() { tlsHandshake = time.Now() },
        TLSHandshakeDone: func(cs tls.ConnectionState, err error) {
            fmt.Printf("TLS Handshake: %v\n", time.Since(tlsHandshake))
        },

        ConnectStart: func(network, addr string) { connect = time.Now() },
        ConnectDone: func(network, addr string, err error) {
            fmt.Printf("Connect time: %v\n", time.Since(connect))
        },

        GotFirstResponseByte: func() {
            fmt.Printf("Time from start to first byte: %v\n", time.Since(start))
        },
    }

    req = req.WithContext(httptrace.WithClientTrace(req.Context(), trace))
    start = time.Now()
    if _, err := http.DefaultTransport.RoundTrip(req); err != nil {
        log.Fatal(err)
    }
    fmt.Printf("Total time: %v\n", time.Since(start))
}

调用它的示例:

timeGet("https://google.com")

输出示例:

DNS Done: 7.998465ms
Connect time: 12.677085ms
TLS Handshake: 128.65394ms
Time from start to first byte: 176.461087ms
Total time: 176.723402ms

另外,请务必查看github.com/davecheney/httpstat,它为您提供了一个CLI实用程序,该实用程序也可以在后台使用该httptracing软件包。

2020-07-02