Created
January 1, 2019 21:00
-
-
Save moorereason/f77d69a2c823fb222eba61c151e63a6b to your computer and use it in GitHub Desktop.
Resty Tracer
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"context" | |
"crypto/tls" | |
"fmt" | |
"net/http/httptrace" | |
"time" | |
"gopkg.in/resty.v1" | |
) | |
type HTTPTracer struct { | |
GetConn time.Time | |
GotConn time.Time | |
GotFirstResponseByte time.Time | |
DNSStart time.Time | |
DNSDone time.Time | |
ConnectStart time.Time | |
ConnectDone time.Time | |
TLSHandshakeStart time.Time | |
TLSHandshakeDone time.Time | |
} | |
func (t *HTTPTracer) Context() context.Context { | |
return httptrace.WithClientTrace( | |
context.Background(), | |
&httptrace.ClientTrace{ | |
GetConn: func(_ string) { t.GetConn = time.Now() }, | |
DNSStart: func(_ httptrace.DNSStartInfo) { t.DNSStart = time.Now() }, | |
DNSDone: func(_ httptrace.DNSDoneInfo) { t.DNSDone = time.Now() }, | |
ConnectStart: func(_, _ string) { | |
if t.DNSDone.IsZero() { | |
t.DNSDone = time.Now() | |
} | |
}, | |
GotConn: func(_ httptrace.GotConnInfo) { t.GotConn = time.Now() }, | |
GotFirstResponseByte: func() { t.GotFirstResponseByte = time.Now() }, | |
TLSHandshakeStart: func() { t.TLSHandshakeStart = time.Now() }, | |
TLSHandshakeDone: func(_ tls.ConnectionState, _ error) { t.TLSHandshakeDone = time.Now() }, | |
}, | |
) | |
} | |
func main() { | |
tr := &HTTPTracer{} | |
_, _ = resty.R(). | |
SetContext(tr.Context()). | |
Get("http://httpbin.org/get") | |
endTime := time.Now() | |
if tr.DNSStart.IsZero() { | |
tr.DNSStart = tr.GetConn | |
tr.DNSDone = tr.GetConn | |
} | |
fmt.Println("DNS Lookup", tr.DNSDone.Sub(tr.DNSStart)) | |
fmt.Println("TCP Connection", tr.GotConn.Sub(tr.DNSDone)) | |
fmt.Println("Server Processing", tr.GotFirstResponseByte.Sub(tr.GotConn)) | |
fmt.Println("TLS Handshake", tr.TLSHandshakeDone.Sub(tr.TLSHandshakeStart)) | |
fmt.Println("Content Transfer", endTime.Sub(tr.GotFirstResponseByte)) | |
fmt.Println("Total Time", endTime.Sub(tr.GetConn)) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment