Skip to content
This repository was archived by the owner on Apr 20, 2023. It is now read-only.
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion httpcache.go
Original file line number Diff line number Diff line change
Expand Up @@ -533,7 +533,7 @@ type cachingReadCloser struct {
func (r *cachingReadCloser) Read(p []byte) (n int, err error) {
n, err = r.R.Read(p)
r.buf.Write(p[:n])
if err == io.EOF {
if err == io.EOF || n < len(p) {
r.OnEOF(bytes.NewReader(r.buf.Bytes()))
}
return n, err
Expand Down
47 changes: 47 additions & 0 deletions httpcache_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package httpcache

import (
"bytes"
"encoding/json"
"errors"
"flag"
"io"
Expand Down Expand Up @@ -158,6 +159,15 @@ func setup() {
}
}
}))

mux.HandleFunc("/json", http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Cache-Control", "max-age=3600")
w.Header().Set("Content-Type", "application/json")
// This will force using bufio.Read() instead of chunkedReader.Read()
// to miss the EOF.
w.Header().Set("Transfer-encoding", "identity")
json.NewEncoder(w).Encode(map[string]string{"k": "v"})
}))
}

func teardown() {
Expand Down Expand Up @@ -398,6 +408,43 @@ func TestCacheOnlyIfBodyRead(t *testing.T) {
}
}

func TestCacheOnJsonBodyRead(t *testing.T) {
resetTest()
{
req, err := http.NewRequest("GET", s.server.URL+"/json", nil)
if err != nil {
t.Fatal(err)
}
resp, err := s.client.Do(req)
if err != nil {
t.Fatal(err)
}
defer resp.Body.Close()
var r json.RawMessage
err = json.NewDecoder(resp.Body).Decode(&r)
if err != nil {
t.Fatal(err)
}
if resp.Header.Get(XFromCache) != "" {
t.Fatalf("XFromCache header isn't blank")
}
}
{
req, err := http.NewRequest("GET", s.server.URL+"/json", nil)
if err != nil {
t.Fatal(err)
}
resp, err := s.client.Do(req)
if err != nil {
t.Fatal(err)
}
defer resp.Body.Close()
if resp.Header.Get(XFromCache) != "1" {
t.Fatalf("XFromCache header isn't set")
}
}
}

func TestOnlyReadBodyOnDemand(t *testing.T) {
resetTest()

Expand Down