From 1bc03b1738df7573d56d68ccbb3754e2d655389f Mon Sep 17 00:00:00 2001 From: Ben Morrison Date: Sat, 9 May 2020 19:38:13 -0400 Subject: cleaned up cache.bap() added cache.insert() to handle locking cache and inserting a page. moved the check for / to the beginning to reduce unnecessary execution if it's just a request for the index. --- cache.go | 35 +++++++++++++++++++---------------- 1 file changed, 19 insertions(+), 16 deletions(-) diff --git a/cache.go b/cache.go index 0967c11..283f698 100644 --- a/cache.go +++ b/cache.go @@ -41,6 +41,17 @@ func (cache *cacheWrapper) checkedInit(path string) { } } +// Adds a given page to the cache with path as the key +func (cache *cacheWrapper) insert(path string, raw []byte) { + cache.Lock() + defer cache.Unlock() + + cache.pages[path] = &page{ + raw: raw, + expires: time.Now().Add(cacheDuration), + } +} + // Returns true if the cached page is good. // False if it's stale. func (cache *cacheWrapper) isFresh(path string) bool { @@ -52,21 +63,20 @@ func (cache *cacheWrapper) isFresh(path string) bool { // Wraps the two cache-checking functions. // One for /, the other for various requests. func (cache *cacheWrapper) bap(requestPath string) error { - var split []string + cache.checkedInit(requestPath) + + if cache.isFresh(requestPath) { + return nil + } + var format, query string if requestPath != "/" { - split = strings.Split(requestPath[1:], "/") + split := strings.Split(requestPath[1:], "/") format = split[0] query = split[1] } - cache.checkedInit(requestPath) - - if cache.isFresh(requestPath) { - return nil - } - var bytes []byte var err error @@ -89,14 +99,7 @@ func (cache *cacheWrapper) bap(requestPath string) error { return err } - cache.Lock() - defer cache.Unlock() - - cache.pages[requestPath] = &page{ - raw: bytes, - expires: time.Now().Add(cacheDuration), - } - + cache.insert(requestPath, bytes) return nil } -- cgit 1.4.1-2-gfad0