diff --git a/fastcache.go b/fastcache.go index f26c43e..c031ab8 100644 --- a/fastcache.go +++ b/fastcache.go @@ -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 @@ -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) diff --git a/fastcache_test.go b/fastcache_test.go index 9c66056..8fa97ce 100644 --- a/fastcache_test.go +++ b/fastcache_test.go @@ -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(), }))) @@ -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)) @@ -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) + } + } +}