Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

🚀 [Feature]: Cache-Control: no-cache #2159

Merged
merged 24 commits into from
Oct 21, 2022
Merged
Show file tree
Hide file tree
Changes from 15 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
10 changes: 10 additions & 0 deletions middleware/cache/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -131,6 +131,13 @@ type Config struct {
//
// Default: []string{fiber.MethodGet, fiber.MethodHead}
Methods []string

// Check if the request header contains Cache-Control: no-cache
//
// Default: func(c *fiber.Ctx) bool {
// return strings.Contains(c.Get(fiber.HeaderCacheControl), "no-cache")
// },
NoCache func(c *fiber.Ctx) bool
}
```

Expand All @@ -151,5 +158,8 @@ var ConfigDefault = Config{
Storage: nil,
MaxBytes: 0,
Methods: []string{fiber.MethodGet, fiber.MethodHead},
NoCache: func(c *fiber.Ctx) bool {
return strings.Contains(c.Get(fiber.HeaderCacheControl), "no-cache")
},
}
```
2 changes: 1 addition & 1 deletion middleware/cache/cache.go
Original file line number Diff line number Diff line change
Expand Up @@ -116,7 +116,7 @@ func New(config ...Config) fiber.Handler {
_, size := heap.remove(e.heapidx)
storedBytes -= size
}
} else if e.exp != 0 {
} else if e.exp != 0 && !cfg.NoCache(c) {
// Separate body value to avoid msgp serialization
// We can store raw bytes with Storage 👍
if cfg.Storage != nil {
Expand Down
127 changes: 127 additions & 0 deletions middleware/cache/cache_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ import (
"time"

"github.com/gofiber/fiber/v2"
"github.com/gofiber/fiber/v2/middleware/etag"
"github.com/gofiber/fiber/v2/internal/storage/memory"
"github.com/gofiber/fiber/v2/utils"
"github.com/valyala/fasthttp"
Expand Down Expand Up @@ -107,6 +108,132 @@ func Test_Cache(t *testing.T) {
utils.AssertEqual(t, cachedBody, body)
}

func Test_Cache_WithCacheControlNoCacheRequestHeader(t *testing.T) {
t.Parallel()

app := fiber.New()
app.Use(New())

app.Get("/", func(c *fiber.Ctx) error {
return c.SendString(c.Query("id", "1"))
})

// Request id = 1
req := httptest.NewRequest("GET", "/", nil)
resp, err := app.Test(req)
utils.AssertEqual(t, nil, err)
utils.AssertEqual(t, "miss", resp.Header.Get("X-Cache"))
// Response cached, entry id = 1

// Request id = 2 without Cache-Control: no-cache
cachedReq := httptest.NewRequest("GET", "/?id=2", nil)
cachedResp, err := app.Test(cachedReq)
defer cachedResp.Body.Close()
cachedBody, _ := ioutil.ReadAll(cachedResp.Body)
utils.AssertEqual(t, nil, err)
utils.AssertEqual(t, "hit", cachedResp.Header.Get("X-Cache"))
utils.AssertEqual(t, []byte("1"), cachedBody)
// Response not cached, returns cached response, entry id = 1

// Request id = 2 with Cache-Control: no-cache
noCacheReq := httptest.NewRequest("GET", "/?id=2", nil)
noCacheReq.Header.Set(fiber.HeaderCacheControl, "no-cache")
noCacheResp, err := app.Test(noCacheReq)
defer noCacheResp.Body.Close()
noCacheBody, _ := ioutil.ReadAll(noCacheResp.Body)
utils.AssertEqual(t, nil, err)
utils.AssertEqual(t, "miss", noCacheResp.Header.Get("X-Cache"))
utils.AssertEqual(t, []byte("2"), noCacheBody)
// Response cached, returns updated response, entry = 2

/* Check Test_Cache_WithETagAndCacheControlNoCacheRequestHeader */
// Request id = 2 with Cache-Control: no-cache again
noCacheReq1 := httptest.NewRequest("GET", "/?id=2", nil)
noCacheReq1.Header.Set(fiber.HeaderCacheControl, "no-cache")
noCacheResp1, err := app.Test(noCacheReq1)
defer noCacheResp1.Body.Close()
noCacheBody1, _ := ioutil.ReadAll(noCacheResp1.Body)
utils.AssertEqual(t, nil, err)
utils.AssertEqual(t, "miss", noCacheResp1.Header.Get("X-Cache"))
utils.AssertEqual(t, []byte("2"), noCacheBody1)
// Response cached, returns updated response, entry = 2

// Request id = 1 without Cache-Control: no-cache
cachedReq1 := httptest.NewRequest("GET", "/", nil)
cachedResp1, err := app.Test(cachedReq1)
defer cachedResp1.Body.Close()
cachedBody1, _ := ioutil.ReadAll(cachedResp1.Body)
utils.AssertEqual(t, nil, err)
utils.AssertEqual(t, "hit", cachedResp1.Header.Get("X-Cache"))
utils.AssertEqual(t, []byte("2"), cachedBody1)
// Response not cached, returns cached response, entry id = 2
}

func Test_Cache_WithETagAndCacheControlNoCacheRequestHeader(t *testing.T) {
t.Parallel()

app := fiber.New()
app.Use(
etag.New(),
New(),
)

app.Get("/", func(c *fiber.Ctx) error {
return c.SendString(c.Query("id", "1"))
})

// Request id = 1
req := httptest.NewRequest("GET", "/", nil)
resp, err := app.Test(req)
utils.AssertEqual(t, nil, err)
utils.AssertEqual(t, "miss", resp.Header.Get("X-Cache"))
utils.AssertEqual(t, fiber.StatusOK, resp.StatusCode)
// Response cached, entry id = 1

// If response status 200
etagToken := resp.Header.Get("Etag")

// Request id = 2 with ETag but without Cache-Control: no-cache
cachedReq := httptest.NewRequest("GET", "/?id=2", nil)
cachedReq.Header.Set(fiber.HeaderIfNoneMatch, etagToken)
cachedResp, err := app.Test(cachedReq)
utils.AssertEqual(t, nil, err)
utils.AssertEqual(t, "hit", cachedResp.Header.Get("X-Cache"))
utils.AssertEqual(t, fiber.StatusNotModified, cachedResp.StatusCode)
// Response not cached, returns cached response, entry id = 1, status not modified

// Request id = 2 with ETag and Cache-Control: no-cache
noCacheReq := httptest.NewRequest("GET", "/?id=2", nil)
noCacheReq.Header.Set(fiber.HeaderCacheControl, "no-cache")
noCacheReq.Header.Set(fiber.HeaderIfNoneMatch, etagToken)
noCacheResp, err := app.Test(noCacheReq)
utils.AssertEqual(t, nil, err)
utils.AssertEqual(t, "miss", noCacheResp.Header.Get("X-Cache"))
utils.AssertEqual(t, fiber.StatusOK, noCacheResp.StatusCode)
// Response cached, returns updated response, entry id = 2

// If response status 200
etagToken = noCacheResp.Header.Get("Etag")

// Request id = 2 with ETag and Cache-Control: no-cache again
noCacheReq1 := httptest.NewRequest("GET", "/?id=2", nil)
noCacheReq1.Header.Set(fiber.HeaderCacheControl, "no-cache")
noCacheReq1.Header.Set(fiber.HeaderIfNoneMatch, etagToken)
noCacheResp1, err := app.Test(noCacheReq1)
utils.AssertEqual(t, nil, err)
utils.AssertEqual(t, "miss", noCacheResp1.Header.Get("X-Cache"))
utils.AssertEqual(t, fiber.StatusNotModified, noCacheResp1.StatusCode)
// Response cached, returns updated response, entry id = 2, status not modified

// Request id = 1 without ETag and Cache-Control: no-cache
cachedReq1 := httptest.NewRequest("GET", "/", nil)
cachedResp1, err := app.Test(cachedReq1)
utils.AssertEqual(t, nil, err)
utils.AssertEqual(t, "hit", cachedResp1.Header.Get("X-Cache"))
utils.AssertEqual(t, fiber.StatusOK, cachedResp1.StatusCode)
// Response not cached, returns cached response, entry id = 2
}

func Test_Cache_WithSeveralRequests(t *testing.T) {
t.Parallel()

Expand Down
15 changes: 15 additions & 0 deletions middleware/cache/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package cache

import (
"fmt"
"strings"
"time"

"github.com/gofiber/fiber/v2"
Expand Down Expand Up @@ -72,6 +73,13 @@ type Config struct {
//
// Default: []string{fiber.MethodGet, fiber.MethodHead}
Methods []string

// Check if the request header contains Cache-Control: no-cache
//
// Default: func(c *fiber.Ctx) bool {
// return strings.Contains(c.Get(fiber.HeaderCacheControl), "no-cache")
// },
NoCache func(c *fiber.Ctx) bool
}

// ConfigDefault is the default config
Expand All @@ -88,6 +96,9 @@ var ConfigDefault = Config{
Storage: nil,
MaxBytes: 0,
Methods: []string{fiber.MethodGet, fiber.MethodHead},
NoCache: func(c *fiber.Ctx) bool {
return strings.Contains(c.Get(fiber.HeaderCacheControl), "no-cache")
},
}

// Helper function to set default values
Expand Down Expand Up @@ -124,5 +135,9 @@ func configDefault(config ...Config) Config {
if len(cfg.Methods) == 0 {
cfg.Methods = ConfigDefault.Methods
}
if cfg.NoCache == nil {
cfg.NoCache = ConfigDefault.NoCache
}

return cfg
}