forked from ardanlabs/gotraining
/
example5.go
70 lines (57 loc) · 1.42 KB
/
example5.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
58
59
60
61
62
63
64
65
66
67
68
69
70
// All material is licensed under the Apache License Version 2.0, January 2004
// http://www.apache.org/licenses/LICENSE-2.0
// Sample program that implements a web request with a context that is
// used to timeout the request if it takes too long.
package main
import (
"context"
"io"
"log"
"net/http"
"os"
"time"
)
func main() {
// Create a new request.
req, err := http.NewRequest("GET", "https://www.goinggo.net/post/index.xml", nil)
if err != nil {
log.Println(err)
return
}
// Create a context with a timeout of 50 milliseconds.
ctx, cancel := context.WithTimeout(req.Context(), 50*time.Millisecond)
defer cancel()
// Declare a new transport and client for the call.
var tr http.Transport
client := http.Client{
Transport: &tr,
}
// Make the web call in a separate goroutine so it can be cancelled.
ch := make(chan error, 1)
go func() {
log.Println("Starting Request")
// Make the web call and return any error.
resp, err := client.Do(req)
if err != nil {
ch <- err
return
}
// Close the response body on the return.
defer resp.Body.Close()
// Write the response to stdout.
io.Copy(os.Stdout, resp.Body)
ch <- nil
}()
// Wait the request or timeout.
select {
case <-ctx.Done():
log.Println("timeout, cancel work...")
// Cancel the request and wait for it to complete.
tr.CancelRequest(req)
log.Println(<-ch)
case err := <-ch:
if err != nil {
log.Println(err)
}
}
}