forked from TykTechnologies/tyk
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmiddleware_redis_cache.go
114 lines (92 loc) · 3.52 KB
/
middleware_redis_cache.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
package main
import (
"bufio"
"bytes"
"crypto/md5"
"encoding/hex"
"github.com/gorilla/context"
"io"
"net/http"
"strconv"
)
// RedisCacheMiddleware is a caching middleware that will pull data from Redis instead of the upstream proxy
type RedisCacheMiddleware struct {
TykMiddleware
CacheStore StorageHandler
}
type RedisCacheMiddlewareConfig struct{}
// New lets you do any initialisations for the object can be done here
func (m *RedisCacheMiddleware) New() {}
// GetConfig retrieves the configuration from the API config - we user mapstructure for this for simplicity
func (m *RedisCacheMiddleware) GetConfig() (interface{}, error) {
var thisModuleConfig RedisCacheMiddlewareConfig
return thisModuleConfig, nil
}
func (m RedisCacheMiddleware) CreateCheckSum(req *http.Request, keyName string) string {
h := md5.New()
io.WriteString(h, req.URL.RawQuery)
reqChecksum := hex.EncodeToString(h.Sum(nil))
cacheKey := m.Spec.APIDefinition.APIID + keyName + reqChecksum
return cacheKey
}
// ProcessRequest will run any checks on the request on the way through the system, return an error to have the chain fail
func (m *RedisCacheMiddleware) ProcessRequest(w http.ResponseWriter, r *http.Request, configuration interface{}) (error, int) {
// Allow global cache disabe
if !m.Spec.APIDefinition.CacheOptions.EnableCache {
return nil, 200
}
var stat RequestStatus
// Only allow idempotent (safe) methods
if r.Method == "GET" || r.Method == "OPTIONS" || r.Method == "HEAD" {
// Lets see if we can throw a sledgehammer at this
if m.Spec.APIDefinition.CacheOptions.CacheAllSafeRequests {
stat = StatusCached
} else {
// New request checker, more targetted, less likely to fail
_, versionPaths, _, _ := m.TykMiddleware.Spec.GetVersionData(r)
found, _ := m.TykMiddleware.Spec.CheckSpecMatchesStatus(r.URL.Path, r.Method, versionPaths, Cached)
if found {
stat = StatusCached
}
}
// Cached route matched, let go
if stat == StatusCached {
authHeaderValue := context.Get(r, AuthHeaderValue).(string)
thisKey := m.CreateCheckSum(r, authHeaderValue)
retBlob, found := m.CacheStore.GetKey(thisKey)
if found != nil {
// Pass through to proxy AND CACHE RESULT
sNP := SuccessHandler{m.TykMiddleware}
reqVal := sNP.ServeHTTP(w, r)
var wireFormatReq bytes.Buffer
reqVal.Write(&wireFormatReq)
m.CacheStore.SetKey(thisKey, wireFormatReq.String(), m.Spec.APIDefinition.CacheOptions.CacheTimeout)
return nil, 666
}
retObj := bytes.NewReader([]byte(retBlob))
asBufioReader := bufio.NewReader(retObj)
newRes, resErr := http.ReadResponse(asBufioReader, r)
if resErr != nil {
log.Error("Could not create response object: ", resErr)
}
defer newRes.Body.Close()
for _, h := range hopHeaders {
newRes.Header.Del(h)
}
copyHeader(w.Header(), newRes.Header)
w.Header().Add("x-tyk-cached-response", "1")
thisSessionState := context.Get(r, SessionData).(SessionState)
w.Header().Set("X-RateLimit-Limit", strconv.Itoa(int(thisSessionState.QuotaMax)))
w.Header().Set("X-RateLimit-Remaining", strconv.Itoa(int(thisSessionState.QuotaRemaining)))
w.Header().Set("X-RateLimit-Reset", strconv.Itoa(int(thisSessionState.QuotaRenews)))
w.WriteHeader(newRes.StatusCode)
m.Proxy.copyResponse(w, newRes.Body)
// Record analytics
sNP := SuccessHandler{m.TykMiddleware}
sNP.RecordHit(w, r, 0)
// Stop any further execution
return nil, 666
}
}
return nil, 200
}