-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcache.go
61 lines (54 loc) · 1.37 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
package main
import (
"fmt"
"net/http"
"time"
"github.com/dblclik/EasyCache/models"
"github.com/labstack/echo/v4"
)
// Get Cache Entry (If Exists)
func getCache(c echo.Context) error {
key := c.QueryParam("key")
if val, exists := CacheMap[key]; exists {
r := &models.CacheResponse{
Exists: true,
Key: key,
Value: val,
Timestamp: time.Now().Format("20060102150405"),
}
return c.JSON(http.StatusOK, r)
}
r := &models.CacheResponse{
Exists: false,
Key: key,
Value: "",
Timestamp: time.Now().Format("20060102150405"),
}
return c.JSON(http.StatusOK, r)
}
// Put Cache Entry, Evict Key If Needed
func putCache(c echo.Context) error {
body := new(models.CacheLoad)
if err := c.Bind(body); err != nil {
return err
}
// if entry is new, prepend to Head of LRUCache, else move item to front
if _, exists := CacheMap[body.Key]; exists {
err := LRUCache.UpdateDLL(body.Key)
fmt.Println(err)
} else {
LRUCache.AddFrontNodeDLL(body.Key)
// worried about this, might be inefficient to unpack LRUCache
// LRUCache = append([]string{body.Key}, LRUCache...)
}
// add value to cache (updating if needed)
CacheMap[body.Key] = body.Value
if len(CacheMap) > CacheLimit {
go evict()
}
r := &models.CacheLoadConfirmation{
Key: body.Key,
Timestamp: time.Now().Format("20060102150405"),
}
return c.JSON(http.StatusOK, r)
}