Standard library / net/http/httptrace
httptrace.WithClientTrace()
Attach request-scoped hooks to a derived context. New hooks run before older hooks for the same event. Hooks may run concurrently and even after a round trip returns. Expected stdout: 'new,old\n'.
Formal Syntax & Structure
go syntaxgo
func WithClientTrace(ctx context.Context, trace *ClientTrace) context.ContextParameters & Attributes
| Name | Type | Description |
|---|---|---|
| ctx | context.Context | Parent or request context carrying trace hooks. |
| trace | *ClientTrace | Callbacks to attach; do not reuse mutable trace state concurrently. |
Return Value
context.Context
Derived context with composed hooks.
Working Example
Example Snippetgo
package main
import ( "context" "fmt" "net/http/httptrace" "strings")
func main() { var order []string ctx := httptrace.WithClientTrace(context.Background(), &httptrace.ClientTrace{GetConn: func(string) { order = append(order, "old") }}) ctx = httptrace.WithClientTrace(ctx, &httptrace.ClientTrace{GetConn: func(string) { order = append(order, "new") }}) httptrace.ContextClientTrace(ctx).GetConn("demo.invalid:80") fmt.Println(strings.Join(order, ","))}
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) }}