diff options
author | Ben Morrison <ben@gbmor.dev> | 2020-05-09 19:38:13 -0400 |
---|---|---|
committer | Ben Morrison <ben@gbmor.dev> | 2020-05-09 19:38:13 -0400 |
commit | 1bc03b1738df7573d56d68ccbb3754e2d655389f (patch) | |
tree | 9242c00abde8862a80606dfb6d0a2a8a12c43172 | |
parent | 9b0d6aab1167a25400dae2a3c85cb4d08a7fa3cf (diff) | |
download | api-1bc03b1738df7573d56d68ccbb3754e2d655389f.tar.gz |
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.
-rw-r--r-- | cache.go | 35 |
1 files 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 } |