|
4 | 4 | "bytes" |
5 | 5 | "errors" |
6 | 6 | "flag" |
| 7 | + "io" |
7 | 8 | "io/ioutil" |
8 | 9 | "net/http" |
9 | 10 | "net/http/httptest" |
@@ -48,6 +49,11 @@ func setup() { |
48 | 49 | w.Header().Set("Cache-Control", "max-age=3600") |
49 | 50 | })) |
50 | 51 |
|
| 52 | + mux.HandleFunc("/method", http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| 53 | + w.Header().Set("Cache-Control", "max-age=3600") |
| 54 | + w.Write([]byte(r.Method)) |
| 55 | + })) |
| 56 | + |
51 | 57 | mux.HandleFunc("/nostore", http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
52 | 58 | w.Header().Set("Cache-Control", "no-store") |
53 | 59 | })) |
@@ -119,6 +125,65 @@ func resetTest() { |
119 | 125 | clock = &realClock{} |
120 | 126 | } |
121 | 127 |
|
| 128 | +// TestCacheableMethod ensures that uncacheable method does not get stored |
| 129 | +// in cache and get incorrectly used for a following cacheable method request. |
| 130 | +func TestCacheableMethod(t *testing.T) { |
| 131 | + resetTest() |
| 132 | + { |
| 133 | + req, err := http.NewRequest("POST", s.server.URL+"/method", nil) |
| 134 | + if err != nil { |
| 135 | + t.Fatal(err) |
| 136 | + } |
| 137 | + resp, err := s.client.Do(req) |
| 138 | + if err != nil { |
| 139 | + t.Fatal(err) |
| 140 | + } |
| 141 | + var buf bytes.Buffer |
| 142 | + _, err = io.Copy(&buf, resp.Body) |
| 143 | + if err != nil { |
| 144 | + t.Fatal(err) |
| 145 | + } |
| 146 | + err = resp.Body.Close() |
| 147 | + if err != nil { |
| 148 | + t.Fatal(err) |
| 149 | + } |
| 150 | + if got, want := buf.String(), "POST"; got != want { |
| 151 | + t.Errorf("got %q, want %q", got, want) |
| 152 | + } |
| 153 | + if resp.StatusCode != http.StatusOK { |
| 154 | + t.Errorf("response status code isn't 200 OK: %v", resp.StatusCode) |
| 155 | + } |
| 156 | + } |
| 157 | + { |
| 158 | + req, err := http.NewRequest("GET", s.server.URL+"/method", nil) |
| 159 | + if err != nil { |
| 160 | + t.Fatal(err) |
| 161 | + } |
| 162 | + resp, err := s.client.Do(req) |
| 163 | + if err != nil { |
| 164 | + t.Fatal(err) |
| 165 | + } |
| 166 | + var buf bytes.Buffer |
| 167 | + _, err = io.Copy(&buf, resp.Body) |
| 168 | + if err != nil { |
| 169 | + t.Fatal(err) |
| 170 | + } |
| 171 | + err = resp.Body.Close() |
| 172 | + if err != nil { |
| 173 | + t.Fatal(err) |
| 174 | + } |
| 175 | + if got, want := buf.String(), "GET"; got != want { |
| 176 | + t.Errorf("got wrong body %q, want %q", got, want) |
| 177 | + } |
| 178 | + if resp.StatusCode != http.StatusOK { |
| 179 | + t.Errorf("response status code isn't 200 OK: %v", resp.StatusCode) |
| 180 | + } |
| 181 | + if resp.Header.Get(XFromCache) != "" { |
| 182 | + t.Errorf("XFromCache header isn't blank") |
| 183 | + } |
| 184 | + } |
| 185 | +} |
| 186 | + |
122 | 187 | func TestGetOnlyIfCachedHit(t *testing.T) { |
123 | 188 | resetTest() |
124 | 189 | { |
|
0 commit comments