Last active
July 28, 2023 15:23
-
-
Save cep21/86ddbaf4e66977fc2b67be84c17989f1 to your computer and use it in GitHub Desktop.
Example of http trace in Go 1.7
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"fmt" | |
"io" | |
"net/http" | |
"net/http/httptest" | |
"net/http/httptrace" | |
"os" | |
) | |
func main() { | |
server := httptest.NewServer(http.HandlerFunc(http.NotFound)) | |
defer server.Close() | |
c := http.Client{} | |
req, err := http.NewRequest("GET", server.URL, nil) | |
if err != nil { | |
panic(err) | |
} | |
trace := &httptrace.ClientTrace{ | |
GotConn: func(connInfo httptrace.GotConnInfo) { | |
fmt.Println("Got Conn") | |
}, | |
ConnectStart: func(network, addr string) { | |
fmt.Println("Dial start") | |
}, | |
ConnectDone: func(network, addr string, err error) { | |
fmt.Println("Dial done") | |
}, | |
GotFirstResponseByte: func() { | |
fmt.Println("First response byte!") | |
}, | |
WroteHeaders: func() { | |
fmt.Println("Wrote headers") | |
}, | |
WroteRequest: func(wr httptrace.WroteRequestInfo) { | |
fmt.Println("Wrote request", wr) | |
}, | |
} | |
req = req.WithContext(httptrace.WithClientTrace(req.Context(), trace)) | |
fmt.Println("Starting request!") | |
resp, err := c.Do(req) | |
if err != nil { | |
panic(err) | |
} | |
io.Copy(os.Stdout, resp.Body) | |
fmt.Println("Done!") | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment