-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcache.go
115 lines (104 loc) · 2.26 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
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
package main;
import (
"fmt"
"sync"
"net/http"
"time"
"github.com/gin-gonic/gin"
)
type CacheEntry struct {
Value string
Expiration int64
Expiry bool
};
type Cache struct {
data map[string]CacheEntry
mu sync.RWMutex
};
func Init() *Cache {
return &Cache{
data: make(map[string]CacheEntry),
}
}
func (c *Cache) Set(key, value string) {
c.mu.Lock()
defer c.mu.Unlock()
expiration := time.Now().AddDate(1,0,0).UnixNano()
c.data[key] = CacheEntry{Value: value, Expiration: expiration, Expiry: false}
}
func (c *Cache) SetT(key, value string, duration time.Duration) {
c.mu.Lock()
defer c.mu.Unlock()
expiration := time.Now().Add(duration).UnixNano()
c.data[key] = CacheEntry{Value: value, Expiration: expiration, Expiry: true}
}
func (c *Cache) Get(key string) (string, bool) {
c.mu.RLock()
defer c.mu.RUnlock()
entry, found := c.data[key]
if !found || (entry.Expiry && entry.Expiration < time.Now().UnixNano()) {
return "", false
}
return entry.Value, true
}
func (c *Cache) CleanUp() {
for {
time.Sleep(time.Minute)
now := time.Now().UnixNano()
c.mu.Lock()
for key, entry := range c.data {
if now > entry.Expiration && entry.Expiry {
delete(c.data, key)
}
}
c.mu.Unlock()
}
}
func main() {
r := gin.Default()
cache := Init()
go cache.CleanUp()
r.GET("/", func(c *gin.Context) {
c.JSON(http.StatusOK, gin.H{
"message": "This is get request",
"detail": "I am coming from server",
})
});
r.GET("/set", func(c *gin.Context) {
key := c.Query("key")
value := c.Query("value")
durationstr, exists := c.GetQuery("duration")
if exists {
fmt.Println(durationstr, exists)
duration, err := time.ParseDuration(durationstr)
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{
"message": err,
})
return
}
go cache.SetT(key, value, duration)
} else {
go cache.Set(key, value)
}
c.JSON(http.StatusOK, gin.H{
"message": "Key updated in cache",
})
})
r.GET("/get", func(c *gin.Context) {
key := c.Query("key")
value, found := cache.Get(key)
if !found {
c.JSON(http.StatusNotFound, gin.H{
"message": "key not present in cache",
"found": found,
})
} else {
c.JSON(http.StatusOK, gin.H{
"value": value,
"found": found,
})
}
})
r.Run("0.0.0.0:5000")
}