implemented a global cache-disabler for use during dev

This commit is contained in:
dtookey 2022-07-19 15:38:31 -04:00
parent 26fbb2908c
commit a5f494730d
2 changed files with 47 additions and 6 deletions

View File

@ -14,6 +14,10 @@ const (
DefaultCacheTimeInMinutes = 15
)
var (
UseCache = true
)
type (
lru map[string]*LruEntry
Lru struct {
@ -97,6 +101,9 @@ func (l *Lru) Put(key string, content *[]byte) {
}
func (l *Lru) Get(key string) (*LruEntry, bool) {
if !UseCache {
return nil, false
}
entry, exists := (*l.entries)[key]
if exists && entry.expires.Before(time.Now()) {
fmt.Println("Cache miss due to expired content")
@ -183,6 +190,8 @@ func GuessMimetype(filePath string) string {
return "image/png"
case "svg":
return "image/svg+xml"
case "css":
return "text/css"
default:
return "application/octet-stream"
}

View File

@ -1,6 +1,7 @@
package servlet
import (
"fmt"
"net/http"
"path"
"strings"
@ -40,13 +41,37 @@ func NewSingleFileRoute(urlPattern string, pathlike string, servlet *VinegarServ
func createSingleFileServletFunction(pathlike string) VinegarHandlerFunction {
cache := cacheutil.NewSingleFileCache(pathlike)
var fun VinegarHandlerFunction = func(w http.ResponseWriter, req *http.Request) {
w.Header().Add(ContentTypeHeaderKey, cache.Mimetype)
if clientAcceptsGzip(req) {
acceptsGzip := clientAcceptsGzip(req)
if cacheutil.UseCache {
var content []byte
if acceptsGzip {
w.Header().Add(ContentEncodingHeaderKey, "gzip")
_, err := w.Write(*cache.CompressedContent)
content = *cache.CompressedContent
} else {
content = *cache.Content
}
w.Header().Add(ContentTypeHeaderKey, cache.Mimetype)
_, err := w.Write(content)
if err != nil {
panic(err)
}
} else {
contents, exists := cacheutil.GetDiskContent(pathlike)
if exists {
fmt.Printf("returning contents: len of %d ", len(*contents))
w.Header().Add(ContentTypeHeaderKey, cache.Mimetype)
_, err := w.Write(*contents)
if err != nil {
panic(err)
}
return
} else {
w.WriteHeader(404)
w.Write(nil)
fmt.Println("returning nothing")
return
}
}
}
@ -57,11 +82,18 @@ func createCompressibleFileServletFunction(basePattern string, pathlike string,
var fun VinegarHandlerFunction = func(w http.ResponseWriter, req *http.Request) {
stub := strings.Replace(req.URL.Path, basePattern, "", 1)
cachedContent, exists := cache.Get(stub)
//i don't like this logic below. we need to streamline this a lot better. it's a twisty jungle right now
if !exists {
content, fileExists := cacheutil.GetDiskContent(path.Join(pathlike, stub))
if fileExists {
if cacheutil.UseCache {
cache.Put(stub, content)
cachedContent, _ = cache.Get(stub)
} else {
w.Header().Add(ContentTypeHeaderKey, cacheutil.GuessMimetype(stub))
w.Write(*content)
return
}
} else {
SendError(w, 404, "Oops! Something went wrong.")
return