Skip to content

Instantly share code, notes, and snippets.

@cep21
Last active July 28, 2023 15:23
Show Gist options
  • Save cep21/86ddbaf4e66977fc2b67be84c17989f1 to your computer and use it in GitHub Desktop.
Save cep21/86ddbaf4e66977fc2b67be84c17989f1 to your computer and use it in GitHub Desktop.
Example of http trace in Go 1.7
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