forked from torbiak/gopl
-
Notifications
You must be signed in to change notification settings - Fork 0
/
first.go
44 lines (42 loc) · 876 Bytes
/
first.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
// ex8.11 prints the first HTTP response received.
package main
import (
"flag"
"fmt"
"log"
"net/http"
"strings"
"sync"
)
func main() {
flag.Parse()
cancel := make(chan struct{})
responses := make(chan *http.Response)
wg := &sync.WaitGroup{}
for _, url := range flag.Args() {
wg.Add(1)
go func(url string) {
defer wg.Done()
req, err := http.NewRequest("HEAD", url, nil)
if err != nil {
log.Printf("HEAD %s: %s", url, err)
return
}
req.Cancel = cancel
resp, err := http.DefaultClient.Do(req)
if err != nil {
log.Printf("HEAD %s: %s", url, err)
return
}
responses <- resp
}(url)
}
resp := <-responses
defer resp.Body.Close()
close(cancel) // Cancel incomplete requests.
fmt.Println(resp.Request.URL)
for name, vals := range resp.Header {
fmt.Printf("%s: %s\n", name, strings.Join(vals, ","))
}
wg.Wait()
}