Standard library / net/http/httptrace
httptrace.GotConnInfo
Reports the transport-owned Conn, Reused, WasIdle and IdleTime (meaningful only when WasIdle is true). Never read, write or close Conn from a tracing hook. Expected stdout: 'false\ntrue\n'.
Formal Syntax & Structure
go syntaxgo
type GotConnInfo struct { Conn net.Conn
Reused bool
WasIdle bool
IdleTime time.Duration}Working Example
Example Snippetgo
package main
import ( "context" "fmt" "io" "net/http" "net/http/httptest" "net/http/httptrace" "sync/atomic")
func main() { s := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { fmt.Fprint(w, "ok") })) defer s.Close() var reused atomic.Bool for i := 0; i < 2; i++ { ctx := httptrace.WithClientTrace(context.Background(), &httptrace.ClientTrace{GotConn: func(info httptrace.GotConnInfo) { reused.Store(info.Reused) }}) res := must(s.Client().Do(must(http.NewRequestWithContext(ctx, "GET", s.URL, nil)))) must(io.ReadAll(res.Body)) check(res.Body.Close()) fmt.Println(reused.Load()) }}
func must[T any](v T, e error) T { if e != nil { panic(e) } return v}func check(e error) { if e != nil { panic(e) }}