-
Notifications
You must be signed in to change notification settings - Fork 1
/
server.go
57 lines (48 loc) · 1.21 KB
/
server.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
package main
import (
"bytes"
"strconv"
"time"
"github.com/buaazp/fasthttprouter"
"github.com/valyala/fasthttp"
)
func (c *Cache) BuildRouter() *fasthttprouter.Router {
var router = fasthttprouter.New()
router.GET("/cache/:key", c.getFromCache)
router.PUT("/cache/:key", c.setFromCache)
router.DELETE("/cache/:key", c.deleteFromCache)
return router
}
func (c *Cache) getFromCache(ctx *fasthttp.RequestCtx) {
if val, ok := c.Get(ctx.UserValue("key")); ok {
ctx.SetContentTypeBytes(val.Content)
ctx.SetBodyStream(bytes.NewReader(val.Data), len(val.Data))
return
}
ctx.Error("Key cache value not found", 404)
}
func (c *Cache) setFromCache(ctx *fasthttp.RequestCtx) {
var ttl int64
if ttlVal, err := strconv.Atoi(string(ctx.FormValue("ttl"))); err == nil {
ttl = int64(ttlVal)
} else {
ttl = DefaultTTL
}
c.Set(ctx.UserValue("key"), &CacheElement{
TTL: time.Now().Add(time.Duration(ttl) * time.Second),
Data: ctx.Request.Body(),
Content: ctx.Request.Header.ContentType(),
})
return
}
func (c *Cache) deleteFromCache(ctx *fasthttp.RequestCtx) {
c.Del(ctx.UserValue("key"))
}
func (c *Cache) StartCleanUpWorker() {
go func() {
for {
c.DelExpired()
time.Sleep(time.Second)
}
}()
}