go http trace分析耗时

 

package main

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

func main() {
	req, _ := http.NewRequest("GET", "https://www.baidu.com", nil)
	// DNS(域名解析)->Dial(建立连接)->TLS(证书认证)->Server Processing(请求和响应)
	var dnsStartTime, connStartTime, tlsHandshakeStartTime, getRespStartTime time.Time
	trace := &httptrace.ClientTrace{
		DNSStart: func(httptrace.DNSStartInfo) {
			dnsStartTime = time.Now()
		},
		DNSDone: func(httptrace.DNSDoneInfo) {
			fmt.Printf("dns cost %d ms\n", time.Since(dnsStartTime).Milliseconds())
		},
		ConnectStart: func(network, addr string) {
			connStartTime = time.Now()
		},
		ConnectDone: func(network, addr string, err error) {
			fmt.Printf("connect cost %d ms\n", time.Since(connStartTime).Milliseconds())
		},
		TLSHandshakeStart: func() {
			tlsHandshakeStartTime = time.Now()
		},
		TLSHandshakeDone: func(tls.ConnectionState, error) {
			fmt.Printf("tls handshake cost %d ms\n", time.Since(tlsHandshakeStartTime).Milliseconds())
		},
		WroteRequest: func(info httptrace.WroteRequestInfo) {
			getRespStartTime = time.Now()
		},
		GotFirstResponseByte: func() {
			fmt.Printf("got resp cost %d ms\n", time.Since(getRespStartTime).Milliseconds())
		},
	}

	req = req.WithContext(httptrace.WithClientTrace(req.Context(), trace))
	reqStartTime := time.Now()
	_, err := http.DefaultTransport.RoundTrip(req)
	fmt.Printf("handle req cost %d ms\n", time.Since(reqStartTime).Milliseconds())
	if err != nil {
		log.Fatal(err)
	}
}

 

image

dns cost+connect cost+tls handshake cost+got resp cost<handle req cost,从连接池中获取连接耗时忽略不计。

posted on 2025-08-17 20:45  王景迁  阅读(8)  评论(0)    收藏  举报

导航