-
Notifications
You must be signed in to change notification settings - Fork 7
/
cache.go
76 lines (62 loc) · 1.5 KB
/
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
package main
import (
"fmt"
"io"
"net/http"
"time"
"github.com/spf13/viper"
"gopkg.in/redis.v4"
)
var cacheWriter *CacheWriter
var usingCache bool
type CacheWriter struct {
ttl time.Duration
defaultWriter http.ResponseWriter
cacheClient *redis.Client
reader *http.Request
}
func (c *CacheWriter) Write(b []byte) (int, error) {
url := c.reader.URL.String()
if c.cacheClient != nil {
fmt.Printf("Setting cache \n")
c.cacheClient.Set(url, b, c.ttl)
}
c.defaultWriter.Write(b)
return 0, nil
}
func DecorateCacheWritter(c *viper.Viper, w http.ResponseWriter, r *http.Request) io.Writer {
cacheEnabled := c.GetBool("enabled")
if cacheEnabled && cacheWriter == nil {
address := c.GetString("address")
port := c.GetString("port")
password := c.GetString("password")
hostname := fmt.Sprintf("%s:%s", address, port)
ttl := time.Duration(c.GetInt("ttl"))
redisClient := redis.NewClient(&redis.Options{
Addr: hostname,
Password: password,
})
cacheWriter = &CacheWriter{
ttl: ttl,
defaultWriter: w,
cacheClient: redisClient,
}
}
if cacheEnabled {
cacheWriter.reader = r
return cacheWriter
}
return w
}
func WriteFromCache(c *viper.Viper, w http.ResponseWriter, r *http.Request) bool {
url := r.URL.String()
fmt.Printf(url)
chartInCache, err := cacheWriter.cacheClient.Get(url).Result()
fmt.Printf("%s", chartInCache)
if err == nil {
fmt.Printf("Getting from cache\n")
w.Write([]byte(chartInCache))
return true
}
return false
}