diff options
author | Ben Morrison <ben@gbmor.dev> | 2020-05-07 18:35:47 -0400 |
---|---|---|
committer | Ben Morrison <ben@gbmor.dev> | 2020-05-07 18:35:47 -0400 |
commit | 281444e000918aa20d486ad71f62ff22afd42860 (patch) | |
tree | f289e8d1e22e21e3e4052b05c74c6a19117cc555 | |
parent | e8970e6aca23b457243688c795844ee85c73f846 (diff) | |
download | api-281444e000918aa20d486ad71f62ff22afd42860.tar.gz |
unifying cache checks
-rw-r--r-- | cache.go | 41 | ||||
-rw-r--r-- | http.go | 2 |
2 files changed, 28 insertions, 15 deletions
diff --git a/cache.go b/cache.go index 88d5dba..e26eed3 100644 --- a/cache.go +++ b/cache.go @@ -24,25 +24,37 @@ var cache = &cacheWrapper{ pages: make(map[string]*page), } -func bapCache(requestPath string) { - cache.RLock() - if cache.pages[requestPath] == nil { - cache.RUnlock() - cacheIndex() - return +// Wraps the two cache-checking functions. +// One for /, the other for various requests. +func (cache *cacheWrapper) bap(requestPath string) { + switch requestPath { + case "/": + bapIndex() + default: + } +} + +// Checks if cache either has expired or has nil copy of +// the index. If so, it yoinks the page from disk and +// sets the expiration time. +func bapIndex() { + if cache.pages["/"] == nil { + cache.Lock() + cache.pages["/"] = &page{ + raw: []byte{}, + expires: time.Time{}, + } + cache.Unlock() } - expires := cache.pages[requestPath].expires + cache.RLock() + expires := cache.pages["/"].expires cache.RUnlock() - if time.Now().After(expires) { - cacheIndex() + if time.Now().Before(expires) { + return } -} -// Pulls the index page from disk and places it into the cache. -// etag is an fnv32 hash of the raw file bytes, truncated if necessary. -func cacheIndex() { bytes, err := ioutil.ReadFile("web/index.txt") if err != nil { log.Printf("Could not read index page: %s", err.Error()) @@ -50,9 +62,10 @@ func cacheIndex() { } cache.Lock() + defer cache.Unlock() + cache.pages["/"] = &page{ raw: bytes, expires: time.Now().Add(5 * time.Minute), } - cache.Unlock() } diff --git a/http.go b/http.go index 93b6d0c..2350bea 100644 --- a/http.go +++ b/http.go @@ -78,7 +78,7 @@ func routingHop(r *http.Request) string { // Yeets the index/summary page to the user func indexHandler(w http.ResponseWriter, r *http.Request) { - bapCache("/") + cache.bap("/") cache.RLock() defer cache.RUnlock() |