-
Notifications
You must be signed in to change notification settings - Fork 0
/
plugin.go
123 lines (109 loc) · 3.14 KB
/
plugin.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
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
package crossover_cache
import (
"bytes"
"context"
"encoding/gob"
"github.com/kotalco/resp"
"log"
"net/http"
)
const (
DefaultCacheExpiry = 15
)
type CachedResponse struct {
StatusCode int
Headers map[string][]string
Body []byte
}
type Config struct {
RedisAddress string
RedisAuth string
CacheExpiry int //in seconds
}
// CreateConfig creates the default plugin configuration.
func CreateConfig() *Config {
return &Config{}
}
type Cache struct {
next http.Handler
name string
redisAuth string
redisAddress string
cacheExpiry int
}
func New(ctx context.Context, next http.Handler, config *Config, name string) (http.Handler, error) {
if config.CacheExpiry == 0 {
config.CacheExpiry = DefaultCacheExpiry
}
gob.Register(CachedResponse{})
handler := &Cache{
next: next,
name: name,
redisAddress: config.RedisAddress,
redisAuth: config.RedisAuth,
cacheExpiry: config.CacheExpiry,
}
return handler, nil
}
func (c *Cache) ServeHTTP(rw http.ResponseWriter, req *http.Request) {
respClient, err := resp.NewRedisClient(c.redisAddress, c.redisAuth)
if err != nil {
rw.WriteHeader(http.StatusInternalServerError)
log.Printf("Failed to create Redis Connection %s", err.Error())
rw.Write([]byte("something went wrong"))
return
}
defer respClient.Close()
// cache key based on the request
cacheKey := req.URL.Path
// retrieve the cached response
cachedData, err := respClient.Get(req.Context(), cacheKey)
if err == nil && cachedData != "" {
// Cache hit - parse the cached response and write it to the original ResponseWriter
var cachedResponse CachedResponse
buffer := bytes.NewBufferString(cachedData)
dec := gob.NewDecoder(buffer)
if err := dec.Decode(&cachedResponse); err == nil {
for key, values := range cachedResponse.Headers {
for _, value := range values {
rw.Header().Add(key, value)
}
}
rw.WriteHeader(cachedResponse.StatusCode)
_, _ = rw.Write(cachedResponse.Body)
return
} else {
log.Printf("Failed to serialize response for caching: %s", err.Error())
_ = respClient.Delete(req.Context(), cacheKey)
}
}
// Cache miss - record the response
recorder := &responseRecorder{
rw: rw,
header: rw.Header().Clone(), // Initialize with the original headers.
}
c.next.ServeHTTP(recorder, req)
// Serialize the response data
cachedResponse := CachedResponse{
StatusCode: recorder.status,
Headers: recorder.Header(), // Convert http.Header to a map for serialization
Body: recorder.body.Bytes(),
}
var buffer bytes.Buffer
enc := gob.NewEncoder(&buffer)
if err := enc.Encode(cachedResponse); err != nil {
log.Printf("Failed to serialize response for caching: %s", err)
http.Error(rw, "Internal Server Error", http.StatusInternalServerError)
return
} else {
// Store the serialized response in Redis
if err := respClient.SetWithTTL(req.Context(), cacheKey, buffer.String(), c.cacheExpiry); err != nil {
log.Printf("Failed to cache response in Redis: %s", err.Error())
}
}
if _, err := rw.Write(recorder.body.Bytes()); err != nil {
log.Printf("Failed to write response body: %s", err)
return
}
return
}