File tree Expand file tree Collapse file tree 2 files changed +49
-4
lines changed Expand file tree Collapse file tree 2 files changed +49
-4
lines changed Original file line number Diff line number Diff line change @@ -29,7 +29,12 @@ type Store interface {
29
29
30
30
func Server (store Store ) http.HandlerFunc {
31
31
return func (writer http.ResponseWriter , request * http.Request ) {
32
- data , _ := store .Fetch (request .Context ())
32
+ data , err := store .Fetch (request .Context ())
33
+
34
+ if err != nil {
35
+ return // todo: log error however you like
36
+ }
37
+
33
38
fmt .Fprint (writer , data )
34
39
}
35
40
}
Original file line number Diff line number Diff line change @@ -2,15 +2,35 @@ package main
2
2
3
3
import (
4
4
"context"
5
+ "errors"
5
6
"net/http"
6
7
"net/http/httptest"
7
8
"testing"
8
9
"time"
9
10
)
10
11
11
- type SpyStore struct {
12
- response string
13
- t * testing.T
12
+ type (
13
+ SpyStore struct {
14
+ response string
15
+ t * testing.T
16
+ }
17
+ SpyResponseWriter struct {
18
+ written bool
19
+ }
20
+ )
21
+
22
+ func (s * SpyResponseWriter ) Header () http.Header {
23
+ s .written = true
24
+ return nil
25
+ }
26
+
27
+ func (s * SpyResponseWriter ) Write ([]byte ) (int , error ) {
28
+ s .written = true
29
+ return 0 , errors .New ("not implemented" )
30
+ }
31
+
32
+ func (s * SpyResponseWriter ) WriteHeader (statusCode int ) {
33
+ s .written = true
14
34
}
15
35
16
36
func (s * SpyStore ) Fetch (ctx context.Context ) (string , error ) {
@@ -70,4 +90,24 @@ func TestServer(t *testing.T) {
70
90
71
91
svr .ServeHTTP (response , request )
72
92
})
93
+
94
+ t .Run ("tells store to cancel work if request cancelled" , func (t * testing.T ) {
95
+ data := "hello, world"
96
+ store := & SpyStore {response : data , t : t }
97
+ svr := Server (store )
98
+
99
+ request := httptest .NewRequest (http .MethodGet , "/" , nil )
100
+
101
+ cancellingCtx , cancel := context .WithCancel (request .Context ())
102
+ time .AfterFunc (5 * time .Millisecond , cancel )
103
+ request = request .WithContext (cancellingCtx )
104
+
105
+ response := & SpyResponseWriter {}
106
+
107
+ svr .ServeHTTP (response , request )
108
+
109
+ if response .written {
110
+ t .Error ("a response should not have been written" )
111
+ }
112
+ })
73
113
}
You can’t perform that action at this time.
0 commit comments