@@ -27,6 +27,7 @@ func TestNoTimeout(t *testing.T) {
27
27
t .Fatalf ("error received from client: %v %v" , err , resp )
28
28
}
29
29
}
30
+
30
31
func TestCancel (t * testing.T ) {
31
32
ctx , cancel := context .WithCancel (context .Background ())
32
33
go func () {
@@ -59,6 +60,44 @@ func TestCancelAfterRequest(t *testing.T) {
59
60
}
60
61
}
61
62
63
+ func TestCancelAfterHangingRequest (t * testing.T ) {
64
+ handler := http .HandlerFunc (func (w http.ResponseWriter , r * http.Request ) {
65
+ w .WriteHeader (http .StatusOK )
66
+ w .(http.Flusher ).Flush ()
67
+ <- w .(http.CloseNotifier ).CloseNotify ()
68
+ })
69
+
70
+ serv := httptest .NewServer (handler )
71
+ defer serv .Close ()
72
+
73
+ ctx , cancel := context .WithCancel (context .Background ())
74
+ resp , err := Get (ctx , nil , serv .URL )
75
+ if err != nil {
76
+ t .Fatalf ("unexpected error in Get: %v" , err )
77
+ }
78
+
79
+ // Cancel befer reading the body.
80
+ // Reading Request.Body should fail, since the request was
81
+ // canceled before anything was written.
82
+ cancel ()
83
+
84
+ done := make (chan struct {})
85
+
86
+ go func () {
87
+ b , err := ioutil .ReadAll (resp .Body )
88
+ if len (b ) != 0 || err == nil {
89
+ t .Errorf (`Read got (%q, %v); want ("", error)` , b , err )
90
+ }
91
+ close (done )
92
+ }()
93
+
94
+ select {
95
+ case <- time .After (1 * time .Second ):
96
+ t .Errorf ("Test timed out" )
97
+ case <- done :
98
+ }
99
+ }
100
+
62
101
func doRequest (ctx context.Context ) (* http.Response , error ) {
63
102
var okHandler = http .HandlerFunc (func (w http.ResponseWriter , r * http.Request ) {
64
103
time .Sleep (requestDuration )
0 commit comments