在golang中获取TTFB(到第一个字节的时间)值 [英] Getting TTFB (time to first byte) value in golang

查看:100
本文介绍了在golang中获取TTFB(到第一个字节的时间)值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am trying to get value TTFB and Connect value

    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的值,连接,总时间即可。

此外,

推荐答案

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

There's builtin support for this since Go 1.7. Go 1.7 added HTTP Tracing, read blog post: Introducing HTTP Tracing

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

You can specify callback functions which get called at the appropriate phases / points when making an HTTP(S) request. You can specify your callback functions by creating a value of httptrace.ClientTrace, and "arm" it using httptrace.WithClientTrace().

下面是一个示例示例,该示例获取URL参数并打印时间的获取方法:

Here's an example function which gets a URL param, and prints the timing of getting it:

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 软件包。

Also be sure to check out github.com/davecheney/httpstat which gives you a CLI utility that also uses the httptracing package under the hood.

这篇关于在golang中获取TTFB(到第一个字节的时间)值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆