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鈥檒l occasionally send you account related emails.

Already on GitHub? Sign in to your account

馃悰 Get unexpected results from cache #1529

Closed
reloadzz opened this issue Sep 13, 2021 · 3 comments 路 Fixed by #1531
Closed

馃悰 Get unexpected results from cache #1529

reloadzz opened this issue Sep 13, 2021 · 3 comments 路 Fixed by #1531

Comments

@reloadzz
Copy link

Fiber version
github.com/gofiber/fiber/v2 v2.18.0
Issue description
Get unexpected results from cache
Code snippet

package test

import (
	"fmt"
	"io/ioutil"
	"net/http"
	"net/http/httptest"
	"strconv"
	"testing"
	"time"

	"github.com/gofiber/fiber/v2"
	"github.com/gofiber/fiber/v2/middleware/cache"
	"github.com/gofiber/utils"
)

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

	app.Use(cache.New(cache.Config{
		CacheControl: true,
		Expiration:   10 * time.Second,
	}))

	app.Get("/:id", func(c *fiber.Ctx) error {
		// log.Println(c.Params("id"))
		return c.SendString(c.Params("id"))
	})

	for {
		for i := 0; i < 10; i++ {
			func(id int) {
				rsp, err := app.Test(httptest.NewRequest(http.MethodGet, fmt.Sprintf("/%d", id), nil))
				utils.AssertEqual(t, nil, err)

				defer rsp.Body.Close()

				idFromServ, err := ioutil.ReadAll(rsp.Body)
				utils.AssertEqual(t, nil, err)

				a, err := strconv.Atoi(string(idFromServ))
				utils.AssertEqual(t, nil, err)

				// SomeTimes,The id is not equal with a
				utils.AssertEqual(t, id, a)
			}(i)
		}
	}
}
@reloadzz
Copy link
Author

KeyGenerator: func(c *fiber.Ctx) string {
	return utils.CopyString(c.Path())
},

this works well,but don't know why

@ReneWerner87
Copy link
Member

in the example you use the memory as storage for the cache, there the path from the context is used directly, because we have a reference here to save allocations in the next request, this memory area is linked and the cache key changes

as you rightly noticed, we should make a copy of the string, this will slow down the middleware a bit, but should be ok

@reloadzz
Copy link
Author

ok,thank you

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

Successfully merging a pull request may close this issue.

2 participants