Standard library / net/http/httptrace

httptrace.ClientTrace

Register optional hooks for one HTTP round trip. GetConn and GotConn report acquisition; PutIdleConn reports HTTP/1 connection return; DNSStart and DNSDone report resolution; ConnectStart and ConnectDone report dial attempts; TLSHandshakeStart and TLSHandshakeDone report TLS; WroteHeaderField, WroteHeaders, Wait100Continue and WroteRequest describe sending; GotFirstResponseByte, Got100Continue and Got1xxResponse describe response events. Hooks can run concurrently, so synchronize shared state. Do not treat this as a complete redirect trace. Expected stdout: 'true\n'.

Formal Syntax & Structure

go syntaxgo
type ClientTrace struct {  GetConn func(hostPort string)
  GotConn func(GotConnInfo)
  PutIdleConn func(err error)
  GotFirstResponseByte func()
  Got100Continue func()
  Got1xxResponse func(code int, header textproto.MIMEHeader) error
  DNSStart func(DNSStartInfo)
  DNSDone func(DNSDoneInfo)
  ConnectStart func(network, addr string)
  ConnectDone func(network, addr string, err error)
  TLSHandshakeStart func()
  TLSHandshakeDone func(tls.ConnectionState, error)
  WroteHeaderField func(key string, value []string)
  WroteHeaders func()
  Wait100Continue func()
  WroteRequest func(WroteRequestInfo)}

Working Example

Example Snippetgo
package main
import (  "context"  "fmt"  "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 got atomic.Bool  ctx := httptrace.WithClientTrace(context.Background(), &httptrace.ClientTrace{GotFirstResponseByte: func() { got.Store(true) }})  req := must(http.NewRequestWithContext(ctx, "GET", s.URL, nil))  res := must(s.Client().Do(req))  defer res.Body.Close()  fmt.Println(got.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)  }}
Go Reference