Skip to content
This repository was archived by the owner on Sep 23, 2021. It is now read-only.

Commit c3b310d

Browse files
authored
Merge pull request #38 from msoedov/caching
Add caching
2 parents df65ad1 + 79a7a4e commit c3b310d

File tree

4 files changed

+35
-14
lines changed

4 files changed

+35
-14
lines changed

.gitignore

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -26,3 +26,4 @@ slides/
2626
main
2727
node_modules
2828
hacker-slides
29+
vendor/

glide.lock

Lines changed: 12 additions & 8 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

glide.yaml

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@ import:
77
- package: github.com/gin-contrib/sessions
88
- package: github.com/gin-gonic/gin
99
version: ^1.2.0
10+
- package: github.com/hashicorp/golang-lru
1011
testImport:
1112
- package: github.com/franela/goblin
1213
version: ^0.0.1

main.go

Lines changed: 21 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,7 @@ import (
1212
haikunator "github.com/atrox/haikunatorgo"
1313
"github.com/gin-contrib/sessions"
1414
"github.com/gin-gonic/gin"
15+
cache "github.com/hashicorp/golang-lru"
1516
"github.com/msoedov/hacker-slides/auth"
1617
"github.com/msoedov/hacker-slides/files"
1718
)
@@ -27,6 +28,10 @@ func NewApp() *gin.Engine {
2728
r := gin.Default()
2829

2930
store := sessions.NewCookieStore([]byte("secret"))
31+
arc, err := cache.NewARC(10)
32+
if err != nil {
33+
log.Fatalf("Failied to allocate cache %#v", err)
34+
}
3035
r.Use(sessions.Sessions(sessionHeader, store))
3136
r.Use(auth.BasicAuth())
3237

@@ -100,11 +105,20 @@ func NewApp() *gin.Engine {
100105
return
101106
}
102107

103-
body, err := ioutil.ReadFile(path)
104-
if err != nil {
105-
panic(err)
108+
var slide string
109+
cached, ok := arc.Get(path)
110+
if ok {
111+
slide = string(cached.([]byte))
112+
} else {
113+
body, err := ioutil.ReadFile(path)
114+
if err != nil {
115+
log.Errorf("Failied to read file %#v", err)
116+
c.Abort()
117+
return
118+
}
119+
slide = string(body)
106120
}
107-
c.String(200, string(body))
121+
c.String(200, slide)
108122
})
109123

110124
r.PUT("/slides.md", func(c *gin.Context) {
@@ -113,11 +127,12 @@ func NewApp() *gin.Engine {
113127
return
114128
}
115129
body, _ := ioutil.ReadAll(c.Request.Body)
116-
ioutil.WriteFile(path, body, 0644)
130+
arc.Add(path, body)
131+
go ioutil.WriteFile(path, body, 0644)
117132
log.WithFields(log.Fields{
118133
"size": len(body),
119134
"file": path,
120-
}).Info("Wrote to file")
135+
}).Info("Async wrote to file")
121136
c.String(200, "")
122137
})
123138

0 commit comments

Comments
 (0)