forked from goenning/go-cache-demo
-
Notifications
You must be signed in to change notification settings - Fork 0
/
middleware.go
39 lines (31 loc) · 804 Bytes
/
middleware.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
package main
import (
"fmt"
"net/http"
"net/http/httptest"
"time"
)
func cached(duration string, handler func(w http.ResponseWriter, r *http.Request)) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
content := storage.Get(r.RequestURI)
if content != nil {
fmt.Print("Cache Hit!\n")
w.Write(content)
} else {
c := httptest.NewRecorder()
handler(c, r)
for k, v := range c.HeaderMap {
w.Header()[k] = v
}
w.WriteHeader(c.Code)
content := c.Body.Bytes()
if d, err := time.ParseDuration(duration); err == nil {
fmt.Printf("New page cached: %s for %s\n", r.RequestURI, duration)
storage.Set(r.RequestURI, content, d)
} else {
fmt.Printf("Page not cached. err: %s\n", err)
}
w.Write(content)
}
})
}