Httptrace Client Round Trip Hooks

Attach httptrace hooks to a request against an httptest loopback server so connection reuse and first-byte arrival are observable without any external network.

GoData Fetching

Code

snippet
package main

import (
	"context"
	"encoding/json"
	"fmt"
	"net/http"
	"net/http/httptest"
	"net/http/httptrace"
)

func main() {
	// 回环服务器:示例离线可跑,探针回调在真实 RoundTrip 中触发
	srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		w.Header().Set("Content-Type", "application/json")
		_ = json.NewEncoder(w).Encode(map[string]string{"status": "ok"})
	}))
	defer srv.Close()

	trace := &httptrace.ClientTrace{
		GetConn: func(hostPort string) {
			fmt.Println("get conn:", hostPort)
		},
		GotFirstResponseByte: func() {
			fmt.Println("first response byte")
		},
	}
	ctx := httptrace.WithClientTrace(context.Background(), trace)
	req, err := http.NewRequestWithContext(ctx, http.MethodGet, srv.URL, nil)
	if err != nil {
		fmt.Println("bad request:", err)
		return
	}

	resp, err := http.DefaultClient.Do(req)
	if err != nil {
		fmt.Println("request failed:", err)
		return
	}
	defer resp.Body.Close()

	var body map[string]string
	if err := json.NewDecoder(resp.Body).Decode(&body); err != nil {
		fmt.Println("bad body:", err)
		return
	}
	fmt.Println("status:", resp.Status, "body:", body["status"])
}

Reading the execution path

Count the function main as the entire surface area of Httptrace Client Round Trip Hooks.

err is inspected at 3 call sites before any result is trusted. defer inverts the usual order — register now, run at return — which is why cleanup cannot be skipped.

Using it

Running the file prints labeled results such as get conn:, first response byte, bad request: — each operation’s effect is visible in the output.

Key statements

if err != nil {
	fmt.Println("bad request:", err)
	return
}
if err != nil {
	fmt.Println("request failed:", err)
	return
}
ctx := httptrace.WithClientTrace(context.Background(), trace)

Interactive Tools for This Topic

FAQ

What does Httptrace Client Round Trip Hooks print when run?
Running the file directly is enough — expect labeled output lines such as `get conn:`, `first response byte`, `bad request:`.