-
Notifications
You must be signed in to change notification settings - Fork 0
/
cache_handler.go
96 lines (77 loc) · 2.09 KB
/
cache_handler.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
package middlewares
import (
"encoding/json"
"fmt"
"strings"
"time"
"github.com/gofiber/fiber/v2"
"github.com/patrickmn/go-cache"
)
func CacheMiddleware(cache *cache.Cache) fiber.Handler {
return func(c *fiber.Ctx) error {
if c.Method() != fiber.MethodGet {
// Only cache GET requests
return c.Next()
}
cacheKey := GenerateCacheKey(c)
// Check if the response is already in the cache
if cached, found := cache.Get(cacheKey); found {
fmt.Println("cache hit")
c.Response().Header.Set("X-Cache-Status", "hit")
// Set custom header for cache hit
return c.JSON(cached)
}
err := c.Next()
if err != nil {
return err
}
// Check if the response is an error
if c.Response().StatusCode() >= 400 {
fmt.Println("cache skip due to error response")
return nil
}
var data interface{}
body := c.Response().Body()
if len(body) > 0 {
// Unmarshal the response body
err = json.Unmarshal(body, &data)
if err != nil {
return c.JSON(fiber.Map{"error": err.Error()})
}
}
// Cache the response for 10 minutes
cache.Set(cacheKey, data, 10*time.Minute)
fmt.Println("cache miss")
c.Response().Header.Set("X-Cache-Status", "miss") // Set custom header for cache miss
return nil
}
}
func GenerateCacheKey(c *fiber.Ctx) string {
// Generate a cache key from the request path and query parameters
cacheKey := c.Path()
// check to see if query params has :short_url
if c.Params("short_url") != "" {
// Exclude query parameters from cache key for PUT and POST requests
if c.Method() != fiber.MethodGet {
cacheKey = strings.Split(cacheKey, "?")[0]
}
return cacheKey
} else {
return cacheKey + "?" + c.Params("short_url")
}
}
// Create a custom middleware to invalidate cache for PUT and POST requests
func InvalidateCacheMiddleware(cache *cache.Cache) fiber.Handler {
return func(c *fiber.Ctx) error {
// Proceed with the request
err := c.Next()
if err != nil {
return err
}
// Invalidate the cache for PUT and POST requests
if c.Method() == fiber.MethodPut || c.Method() == fiber.MethodPost {
cache.Flush()
}
return nil
}
}