Skip to content

Commit

Permalink
Add mutex for writing to result
Browse files Browse the repository at this point in the history
Fixes tcnksm#21.
  • Loading branch information
kylecarbs committed Aug 31, 2022
1 parent e866bb2 commit c914520
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 0 deletions.
18 changes: 18 additions & 0 deletions go18.go
Original file line number Diff line number Diff line change
Expand Up @@ -41,17 +41,23 @@ func (r *Result) Total(t time.Time) time.Duration {
func withClientTrace(ctx context.Context, r *Result) context.Context {
return httptrace.WithClientTrace(ctx, &httptrace.ClientTrace{
DNSStart: func(i httptrace.DNSStartInfo) {
r.mutex.Lock()
defer r.mutex.Unlock()
r.dnsStart = time.Now()
},

DNSDone: func(i httptrace.DNSDoneInfo) {
r.mutex.Lock()
defer r.mutex.Unlock()
r.dnsDone = time.Now()

r.DNSLookup = r.dnsDone.Sub(r.dnsStart)
r.NameLookup = r.dnsDone.Sub(r.dnsStart)
},

ConnectStart: func(_, _ string) {
r.mutex.Lock()
defer r.mutex.Unlock()
r.tcpStart = time.Now()

// When connecting to IP (When no DNS lookup)
Expand All @@ -62,25 +68,33 @@ func withClientTrace(ctx context.Context, r *Result) context.Context {
},

ConnectDone: func(network, addr string, err error) {
r.mutex.Lock()
defer r.mutex.Unlock()
r.tcpDone = time.Now()

r.TCPConnection = r.tcpDone.Sub(r.tcpStart)
r.Connect = r.tcpDone.Sub(r.dnsStart)
},

TLSHandshakeStart: func() {
r.mutex.Lock()
defer r.mutex.Unlock()
r.isTLS = true
r.tlsStart = time.Now()
},

TLSHandshakeDone: func(_ tls.ConnectionState, _ error) {
r.mutex.Lock()
defer r.mutex.Unlock()
r.tlsDone = time.Now()

r.TLSHandshake = r.tlsDone.Sub(r.tlsStart)
r.Pretransfer = r.tlsDone.Sub(r.dnsStart)
},

GotConn: func(i httptrace.GotConnInfo) {
r.mutex.Lock()
defer r.mutex.Unlock()
// Handle when keep alive is used and connection is reused.
// DNSStart(Done) and ConnectStart(Done) is skipped
if i.Reused {
Expand All @@ -89,6 +103,8 @@ func withClientTrace(ctx context.Context, r *Result) context.Context {
},

WroteRequest: func(info httptrace.WroteRequestInfo) {
r.mutex.Lock()
defer r.mutex.Unlock()
r.serverStart = time.Now()

// When client doesn't use DialContext or using old (before go1.7) `net`
Expand Down Expand Up @@ -123,6 +139,8 @@ func withClientTrace(ctx context.Context, r *Result) context.Context {
},

GotFirstResponseByte: func() {
r.mutex.Lock()
defer r.mutex.Unlock()
r.serverDone = time.Now()

r.ServerProcessing = r.serverDone.Sub(r.serverStart)
Expand Down
3 changes: 3 additions & 0 deletions httpstat.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,11 +8,14 @@ import (
"fmt"
"io"
"strings"
"sync"
"time"
)

// Result stores httpstat info.
type Result struct {
mutex sync.Mutex

// The following are duration for each phase
DNSLookup time.Duration
TCPConnection time.Duration
Expand Down

0 comments on commit c914520

Please sign in to comment.