Cache middleware now records the response and writes that to the DB

This commit is contained in:
Jan-Lukas Else 2020-07-30 16:43:04 +02:00
parent 2639cd9f3b
commit 65ce24d410
3 changed files with 38 additions and 21 deletions

View File

@ -2,7 +2,9 @@ package main
import (
"context"
"encoding/json"
"net/http"
"net/http/httptest"
"net/url"
"time"
)
@ -10,18 +12,36 @@ import (
func CacheMiddleware(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
requestUrl, _ := url.ParseRequestURI(r.RequestURI)
path := SlashTrimmedPath(r)
if appConfig.cache.enable &&
// Check bypass query
!(requestUrl != nil && requestUrl.Query().Get("cache") == "0") {
mime, t, cache := getCache(SlashTrimmedPath(r), r.Context())
if cache == nil {
next.ServeHTTP(w, r)
cacheTime, header, body := getCache(path, r.Context())
if cacheTime == 0 {
recorder := httptest.NewRecorder()
next.ServeHTTP(recorder, r)
// Copy values from recorder
code := recorder.Code
// Send response
for k, v := range recorder.Header() {
w.Header()[k] = v
}
w.Header().Set("GoBlog-Cache", "MISS")
w.WriteHeader(code)
_, _ = w.Write(recorder.Body.Bytes())
// Save cache
if code == http.StatusOK {
saveCache(path, recorder.Header(), recorder.Body.Bytes())
}
return
} else {
expiresTime := time.Unix(t+appConfig.cache.expiration, 0).Format(time.RFC1123)
expiresTime := time.Unix(cacheTime+appConfig.cache.expiration, 0).Format(time.RFC1123)
for k, v := range header {
w.Header()[k] = v
}
w.Header().Set("Expires", expiresTime)
w.Header().Set("Content-Type", mime)
_, _ = w.Write(cache)
w.Header().Set("GoBlog-Cache", "HIT")
_, _ = w.Write(body)
}
} else {
next.ServeHTTP(w, r)
@ -29,25 +49,26 @@ func CacheMiddleware(next http.Handler) http.Handler {
})
}
func getCache(path string, context context.Context) (string, int64, []byte) {
var mime string
var t int64
var cache []byte
func getCache(path string, context context.Context) (creationTime int64, header map[string][]string, body []byte) {
var headerBytes []byte
allowedTime := time.Now().Unix() - appConfig.cache.expiration
row := appDb.QueryRowContext(context, "select COALESCE(mime, ''), COALESCE(time, 0), value from cache where path=? and time>=?", path, allowedTime)
_ = row.Scan(&mime, &t, &cache)
return mime, t, cache
row := appDb.QueryRowContext(context, "select COALESCE(time, 0), header, body from cache where path=? and time>=?", path, allowedTime)
_ = row.Scan(&creationTime, &headerBytes, &body)
header = make(map[string][]string)
_ = json.Unmarshal(headerBytes, &header)
return
}
func saveCache(path string, mime string, value []byte) {
func saveCache(path string, header map[string][]string, body []byte) {
now := time.Now().Unix()
headerBytes, _ := json.Marshal(header)
startWritingToDb()
tx, err := appDb.Begin()
if err != nil {
return
}
_, _ = tx.Exec("delete from cache where time<?;", now-appConfig.cache.expiration)
_, _ = tx.Exec("insert or replace into cache (path, time, mime, value) values (?, ?, ?, ?);", path, now, mime, value)
_, _ = tx.Exec("insert or replace into cache (path, time, header, body) values (?, ?, ?, ?);", path, now, headerBytes, body)
_ = tx.Commit()
finishWritingToDb()
}

View File

@ -34,7 +34,7 @@ func migrateDb() error {
&migrator.Migration{
Name: "00004",
Func: func(tx *sql.Tx) error {
_, err := tx.Exec("create table cache (path text not null primary key, time integer, mime text, value blob);")
_, err := tx.Exec("create table cache (path text not null primary key, time integer, header blob, body blob);")
return err
},
},

View File

@ -32,11 +32,7 @@ func servePost(w http.ResponseWriter, r *http.Request) {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
mime := "text/html"
if appConfig.cache.enable {
saveCache(path, mime, htmlContent)
}
w.Header().Set("Content-Type", mime)
w.Header().Set("Content-Type", "text/html")
_, _ = w.Write(htmlContent)
}