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

时间:2018-01-03 12:08:18

标签: http curl 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

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

另外,有没有办法在不专门使用curl的情况下获取值?

1 个答案:

答案 0 :(得分:10)

自Go 1.7以来,内置了对此的支持。 Go 1.7添加了HTTP跟踪,阅读博文:Introducing HTTP Tracing

您可以指定在发出HTTP(S)请求时在适当的阶段/点调用的回调函数。您可以通过创建值httptrace.ClientTrace和" arm"来指定回调函数。它使用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软件包。