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.
Code
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
cURL to Python & Go ConverterTranslate curl CLI commands with headers, auth, JSON bodies, and timeouts into ready-to-run Python requests and Go net/http client code snippets.Accept Header ParserParse an Accept header into media ranges with their quality values and specificity, sorted by preference for content negotiation debugging.Basic & Bearer Auth Header ToolEncode and decode HTTP Authorization Basic and Bearer headers locally with UTF-8 Base64 validation and automatic JWT claim and expiry inspection.Set-Cookie ParserParse one or more Set-Cookie header values into the cookie name, value, and attributes like Path, Domain, Expires, Max-Age, Secure, HttpOnly, and SameSite.
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:`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.