Skip to content

Instantly share code, notes, and snippets.

@aybabtme
Created July 12, 2023 22:27
Show Gist options
  • Save aybabtme/6e0fa1ba55d38738450166b4250d3025 to your computer and use it in GitHub Desktop.
Save aybabtme/6e0fa1ba55d38738450166b4250d3025 to your computer and use it in GitHub Desktop.
import "net/http/httptrace"
func (cl *httpClient) makeTrace(kvs []*kvpb.KV) *httptrace.ClientTrace {
start := cl.timeNow()
var (
startDial = start
startDNS = start
startConnect = start
startTLS = start
)
return &httptrace.ClientTrace{
GetConn: func(hostPort string) {
startDial = cl.timeNow()
},
GotConn: func(httptrace.GotConnInfo) {
cl.measureDuration("http_call_get_conn_duration", kvs, startDial, cl.timeNow(), "tcp", "dial")
},
DNSStart: func(httptrace.DNSStartInfo) {
startDNS = cl.timeNow()
},
DNSDone: func(dnsif httptrace.DNSDoneInfo) {
kvs := kvs
if dnsif.Err != nil {
kvs = append(kvs, &kvpb.KV{Key: "err", Value: dnsif.Err.Error()})
}
cl.measureDuration("http_call_resolve_dns_duration", kvs, startDNS, cl.timeNow(), "dns", "resolve")
},
ConnectStart: func(network, addr string) {
startConnect = cl.timeNow()
},
ConnectDone: func(network, addr string, err error) {
kvs := append(kvs,
&kvpb.KV{Key: "network", Value: network},
&kvpb.KV{Key: "addr", Value: addr},
)
if err != nil {
kvs = append(kvs, &kvpb.KV{Key: "err", Value: err.Error()})
}
cl.measureDuration("http_call_connect_duration", kvs, startConnect, cl.timeNow(), "tcp", "connect")
},
TLSHandshakeStart: func() {
startTLS = cl.timeNow()
},
TLSHandshakeDone: func(cs tls.ConnectionState, err error) {
kvs := append(kvs,
&kvpb.KV{Key: "nego_proto", Value: cs.NegotiatedProtocol},
&kvpb.KV{Key: "server_name", Value: cs.ServerName},
)
if err != nil {
kvs = append(kvs, &kvpb.KV{Key: "err", Value: err.Error()})
}
cl.measureDuration("http_call_tls_handshake_duration", kvs, startTLS, cl.timeNow(), "tcp", "tls_handshake")
},
GotFirstResponseByte: func() {
cl.measureDuration("http_response_first_byte_duration", kvs, start, cl.timeNow(), "http", "first_bytes")
},
WroteHeaders: func() {
cl.measureDuration("http_request_wrote_header_duration", kvs, start, cl.timeNow(), "http", "wrote_header")
},
WroteRequest: func(wrif httptrace.WroteRequestInfo) {
kvs := kvs
if wrif.Err != nil {
kvs = append(kvs, &kvpb.KV{Key: "err", Value: wrif.Err.Error()})
}
cl.measureDuration("http_request_wrote_request_duration", kvs, start, cl.timeNow(), "http", "wrote_request")
},
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment