forked from PacktPublishing/Mastering-Go-Second-Edition
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathhttpTrace.go
57 lines (50 loc) · 1.09 KB
/
httpTrace.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
package main
import (
"fmt"
"io"
"net/http"
"net/http/httptrace"
"os"
)
func main() {
if len(os.Args) != 2 {
fmt.Printf("Usage: URL\n")
return
}
URL := os.Args[1]
client := http.Client{}
req, _ := http.NewRequest("GET", URL, nil)
trace := &httptrace.ClientTrace{
GotFirstResponseByte: func() {
fmt.Println("First response byte!")
},
GotConn: func(connInfo httptrace.GotConnInfo) {
fmt.Printf("Got Conn: %+v\n", connInfo)
},
DNSDone: func(dnsInfo httptrace.DNSDoneInfo) {
fmt.Printf("DNS Info: %+v\n", dnsInfo)
},
ConnectStart: func(network, addr string) {
fmt.Println("Dial start")
},
ConnectDone: func(network, addr string, err error) {
fmt.Println("Dial done")
},
WroteHeaders: func() {
fmt.Println("Wrote headers")
},
}
req = req.WithContext(httptrace.WithClientTrace(req.Context(), trace))
fmt.Println("Requesting data from server!")
_, err := http.DefaultTransport.RoundTrip(req)
if err != nil {
fmt.Println(err)
return
}
response, err := client.Do(req)
if err != nil {
fmt.Println(err)
return
}
io.Copy(os.Stdout, response.Body)
}