Skip to content

Commit

Permalink
Add a no blob option to skip storing response body.
Browse files Browse the repository at this point in the history
Some usecases may require an ETag cache without actually storing
the response body. This patch introduces a `NoBlob` option which when
set skips caching the response blob but creates a cache entry with
an ETag.
  • Loading branch information
knadh committed Sep 20, 2022
1 parent 4f5d75c commit 1d2547a
Show file tree
Hide file tree
Showing 2 changed files with 42 additions and 1 deletion.
12 changes: 11 additions & 1 deletion fastcache.go
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,11 @@ type Options struct {
// Process ETags and send 304s?
ETag bool

// By default, handler response bodies are cached and served. If this is
// enabled, only ETags are cached and for response bodies, the original
// handler is invoked.
NoBlob bool

// Logger is the optional logger to which errors will be written.
Logger *log.Logger

Expand Down Expand Up @@ -210,10 +215,15 @@ func (f *FastCache) cache(r *fastglue.Request, namespace, group string, o *Optio
}
uri := hex.EncodeToString(hash[:])

var blob []byte
if !o.NoBlob {
blob = r.RequestCtx.Response.Body()
}

err := f.s.Put(namespace, group, uri, Item{
ETag: etag,
ContentType: r.RequestCtx.Response.Header.ContentType(),
Blob: r.RequestCtx.Response.Body(),
Blob: blob,
}, o.TTL)
if err != nil && o.Logger != nil {
return fmt.Errorf("error writing cache to store: %v", err)
Expand Down
31 changes: 31 additions & 0 deletions fastcache_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,14 @@ func init() {
Logger: log.New(os.Stdout, "", log.Ldate|log.Ltime|log.Lshortfile),
}

noBlob = &fastcache.Options{
NamespaceKey: namespaceKey,
ETag: true,
TTL: time.Second * 60,
NoBlob: true,
Logger: log.New(os.Stdout, "", log.Ldate|log.Ltime|log.Lshortfile),
}

fc = fastcache.New(cachestore.New("CACHE:", redis.NewClient(&redis.Options{
Addr: rd.Addr(),
})))
Expand All @@ -62,6 +70,10 @@ func init() {
return r.SendBytes(200, "text/plain", []byte("ok"))
}, ttlShort, group))

srv.GET("/no-blob", fc.Cached(func(r *fastglue.Request) error {
return r.SendBytes(200, "text/plain", []byte("ok"))
}, noBlob, group))

srv.GET("/clear-group", fc.ClearGroup(func(r *fastglue.Request) error {
return r.SendBytes(200, "text/plain", []byte("ok"))
}, ttlShort, group))
Expand Down Expand Up @@ -158,3 +170,22 @@ func TestNoCache(t *testing.T) {
}
}
}

func TestNoBlob(t *testing.T) {
// All requests should return 200.
eTag := ""
for n := 0; n < 3; n++ {
r, _ := getReq(srvRoot+"/no-blob", eTag, t)
if n == 0 {
eTag = r.Header.Get("Etag")
if r.StatusCode != 200 {
t.Fatalf("expected 200 but got %v", r.StatusCode)
}
continue
}

if r.StatusCode != 304 {
t.Fatalf("expected 304 but got %v", r.StatusCode)
}
}
}

0 comments on commit 1d2547a

Please sign in to comment.