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

Commit

Permalink
Merge pull request #38 from msoedov/caching
Browse files Browse the repository at this point in the history
Add caching
  • Loading branch information
msoedov committed Feb 25, 2018
2 parents df65ad1 + 79a7a4e commit c3b310d
Show file tree
Hide file tree
Showing 4 changed files with 35 additions and 14 deletions.
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -26,3 +26,4 @@ slides/
main
node_modules
hacker-slides
vendor/
20 changes: 12 additions & 8 deletions glide.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions glide.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import:
- package: github.com/gin-contrib/sessions
- package: github.com/gin-gonic/gin
version: ^1.2.0
- package: github.com/hashicorp/golang-lru
testImport:
- package: github.com/franela/goblin
version: ^0.0.1
27 changes: 21 additions & 6 deletions main.go
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ import (
haikunator "github.com/atrox/haikunatorgo"
"github.com/gin-contrib/sessions"
"github.com/gin-gonic/gin"
cache "github.com/hashicorp/golang-lru"
"github.com/msoedov/hacker-slides/auth"
"github.com/msoedov/hacker-slides/files"
)
Expand All @@ -27,6 +28,10 @@ func NewApp() *gin.Engine {
r := gin.Default()

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

Expand Down Expand Up @@ -100,11 +105,20 @@ func NewApp() *gin.Engine {
return
}

body, err := ioutil.ReadFile(path)
if err != nil {
panic(err)
var slide string
cached, ok := arc.Get(path)
if ok {
slide = string(cached.([]byte))
} else {
body, err := ioutil.ReadFile(path)
if err != nil {
log.Errorf("Failied to read file %#v", err)
c.Abort()
return
}
slide = string(body)
}
c.String(200, string(body))
c.String(200, slide)
})

r.PUT("/slides.md", func(c *gin.Context) {
Expand All @@ -113,11 +127,12 @@ func NewApp() *gin.Engine {
return
}
body, _ := ioutil.ReadAll(c.Request.Body)
ioutil.WriteFile(path, body, 0644)
arc.Add(path, body)
go ioutil.WriteFile(path, body, 0644)
log.WithFields(log.Fields{
"size": len(body),
"file": path,
}).Info("Wrote to file")
}).Info("Async wrote to file")
c.String(200, "")
})

Expand Down

0 comments on commit c3b310d

Please sign in to comment.