Golang里面怎样获取http请求到响应花费的时间?

2020年7月31日 评论 165 views 1251字阅读4分10秒

Golang 1.7 加了个http-tracing的功能,看这个官方博客介绍https://blog.golang.org/http-tracing

package main

import "crypto/tls"
import "fmt"
import "time"
import "net/http"
import "net/http/httptrace"
import "log"

func main() {
    timeGet("http://www.baidu.com")
}
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))
}

结果

DNS Done: 10.402422ms
Connect time: 4.336225ms
Time from start to first byte: 24.287813ms
Total time: 24.752966ms

引用于:https://www.tianfu.im/topic/6717715326014993

weinxin
公众号
在号内与我交流,回复【资源】获取技术大礼包
Golang最后更新:2020-8-31
小熊