From d32d40c51d41138c24306e2f7ad29d513e2bf766 Mon Sep 17 00:00:00 2001 From: Henry Henderson Date: Wed, 3 Jul 2024 13:39:13 -0400 Subject: [PATCH 1/2] Add some additional functionality to client - Ability to drop the cache from a request. Useful if the client is propagated through the request's life (e.g. call on a PUT/DELETE, etc.) - Add options on a client. Perhaps you apply different TTL or settings for a particular request in your own middleware, etc. --- .gitignore | 5 ++++- cache.go | 26 ++++++++++++++++++++++++++ 2 files changed, 30 insertions(+), 1 deletion(-) diff --git a/.gitignore b/.gitignore index 42cd73d..efbba5d 100644 --- a/.gitignore +++ b/.gitignore @@ -1 +1,4 @@ -/vendor/ \ No newline at end of file +/vendor/ +.idea/ +.vs/ +.vscode/ diff --git a/cache.go b/cache.go index 3bf46cf..429551a 100644 --- a/cache.go +++ b/cache.go @@ -159,6 +159,32 @@ func (c *Client) Middleware(next http.Handler) http.Handler { }) } +// Drop releases the underlying cache for the request's URL. +func (c *Client) Drop(r *http.Request) { + params := r.URL.Query() + key := generateKey(r.URL.String()) + + if _, ok := params[c.refreshKey]; ok { + delete(params, c.refreshKey) + + r.URL.RawQuery = params.Encode() + key = generateKey(r.URL.String()) + } + + c.adapter.Release(key) +} + +// AddOptions allows the addition or re-application of options after a client has been created. +func (c *Client) AddOptions(opts ...ClientOption) error { + for _, opt := range opts { + if err := opt(c); err != nil { + return err + } + } + + return nil +} + func (c *Client) cacheableMethod(method string) bool { for _, m := range c.methods { if method == m { From d5b121370e434faec6e9e1699e6e68ce13fb2825 Mon Sep 17 00:00:00 2001 From: Henry Henderson Date: Wed, 3 Jul 2024 14:35:44 -0400 Subject: [PATCH 2/2] Fix key generation on POST for Drop method --- cache.go | 12 ++++++++++++ 1 file changed, 12 insertions(+) diff --git a/cache.go b/cache.go index 429551a..d9ead4e 100644 --- a/cache.go +++ b/cache.go @@ -164,6 +164,18 @@ func (c *Client) Drop(r *http.Request) { params := r.URL.Query() key := generateKey(r.URL.String()) + if r.Method == http.MethodPost && r.Body != nil { + body, err := io.ReadAll(r.Body) + defer r.Body.Close() + if err != nil { + return + } + + reader := io.NopCloser(bytes.NewBuffer(body)) + key = generateKeyWithBody(r.URL.String(), body) + r.Body = reader + } + if _, ok := params[c.refreshKey]; ok { delete(params, c.refreshKey)