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

ajust config.Next position #1135

Merged
merged 1 commit into from
Jan 31, 2021
Merged
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
10 changes: 5 additions & 5 deletions middleware/cache/cache.go
Original file line number Diff line number Diff line change
Expand Up @@ -43,11 +43,6 @@ func New(config ...Config) fiber.Handler {

// Return new handler
return func(c *fiber.Ctx) error {
// Don't execute middleware if Next returns true
if cfg.Next != nil && cfg.Next(c) {
return c.Next()
}

// Only cache GET methods
if c.Method() != fiber.MethodGet {
return c.Next()
Expand Down Expand Up @@ -105,6 +100,11 @@ func New(config ...Config) fiber.Handler {
return err
}

// Don't cache response if Next returns true
if cfg.Next != nil && cfg.Next(c) {
return nil
}

// Cache response
e.body = utils.SafeBytes(c.Response().Body())
e.status = c.Response().StatusCode()
Expand Down
38 changes: 38 additions & 0 deletions middleware/cache/cache_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -231,6 +231,44 @@ func Test_Cache_NothingToCache(t *testing.T) {
}
}

func Test_Cache_CustomNext(t *testing.T) {
app := fiber.New()

app.Use(New(Config{
Next: func(c *fiber.Ctx) bool {
return !(c.Response().StatusCode() == fiber.StatusOK)
},
CacheControl: true,
}))

app.Get("/", func(c *fiber.Ctx) error {
return c.SendString(time.Now().String())
})

app.Get("/error", func(c *fiber.Ctx) error {
return c.Status(fiber.StatusInternalServerError).SendString(time.Now().String())
})

resp, err := app.Test(httptest.NewRequest("GET", "/", nil))
utils.AssertEqual(t, nil, err)
body, err := ioutil.ReadAll(resp.Body)
utils.AssertEqual(t, nil, err)

respCached, err := app.Test(httptest.NewRequest("GET", "/", nil))
utils.AssertEqual(t, nil, err)
bodyCached, err := ioutil.ReadAll(respCached.Body)
utils.AssertEqual(t, nil, err)
utils.AssertEqual(t, true, bytes.Equal(body, bodyCached))
utils.AssertEqual(t, true, respCached.Header.Get(fiber.HeaderCacheControl) != "")

_, err = app.Test(httptest.NewRequest("GET", "/error", nil))
utils.AssertEqual(t, nil, err)

errRespCached, err := app.Test(httptest.NewRequest("GET", "/error", nil))
utils.AssertEqual(t, nil, err)
utils.AssertEqual(t, true, errRespCached.Header.Get(fiber.HeaderCacheControl) == "")
}

func Test_CustomKey(t *testing.T) {
app := fiber.New()
var called bool
Expand Down