about summary refs log tree commit diff stats
path: root/cache.go
diff options
context:
space:
mode:
authorBen Morrison <ben@gbmor.dev>2020-05-07 18:35:47 -0400
committerBen Morrison <ben@gbmor.dev>2020-05-07 18:35:47 -0400
commit281444e000918aa20d486ad71f62ff22afd42860 (patch)
treef289e8d1e22e21e3e4052b05c74c6a19117cc555 /cache.go
parente8970e6aca23b457243688c795844ee85c73f846 (diff)
downloadapi-281444e000918aa20d486ad71f62ff22afd42860.tar.gz
unifying cache checks
Diffstat (limited to 'cache.go')
-rw-r--r--cache.go41
1 files changed, 27 insertions, 14 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()
 }