about summary refs log tree commit diff stats
path: root/cache.go
blob: be0008380909312a5f47716a303848651843f2e3 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
package main

import (
	"errors"
	"io/ioutil"
	"log"
	"strings"
	"sync"
	"time"
)

const cacheDuration = 1 * time.Minute

// Holds the cached responses
type page struct {
	raw     []byte
	expires time.Time
}

// Wraps the page cache map with a rwlock
type cacheWrapper struct {
	sync.RWMutex
	pages map[string]*page
}

// The actual page/response cache
var cache = &cacheWrapper{
	pages: make(map[string]*page),
}

// Checks if a page exists in the cache already.
// If it doesn't, creates an empty entry.
func (cache *cacheWrapper) checkedInit(path string) {
	cache.Lock()
	defer cache.Unlock()

	if cache.pages[path] == nil {
		cache.pages[path] = &page{
			raw:     []byte{},
			expires: time.Time{},
		}
	}
}

// Returns true if the cached page is good.
// False if it's stale.
func (cache *cacheWrapper) isFresh(path string) bool {
	cache.RLock()
	defer cache.RUnlock()
	return time.Now().Before(cache.pages[path].expires)
}

// Wraps the two cache-checking functions.
// One for /, the other for various requests.
func (cache *cacheWrapper) bap(requestPath string) {
	var split []string
	var format, query string

	if requestPath != "/" {
		split = strings.Split(requestPath[1:], "/")
		format = split[0]
		query = split[1]
	}

	cache.checkedInit(requestPath)

	if cache.isFresh(requestPath) {
		return
	}

	var bytes []byte
	var err error

	switch query {
	case "osversion":
		bytes, err = osVersionQuery(format)
	case "uptime":
		bytes, err = uptimeQuery(format)
	case "usercount":
		bytes, err = userCountQuery(format)
	default:
		if requestPath == "/" {
			bytes, err = ioutil.ReadFile("web/index.txt")
		} else {
			err = errors.New("Invalid Query Type")
		}
	}

	if err != nil {
		log.Printf("Request error %s :: %s", requestPath, err.Error())
		bytes = []byte("Internal Error")
	}

	cache.Lock()
	defer cache.Unlock()

	cache.pages[requestPath] = &page{
		raw:     bytes,
		expires: time.Now().Add(cacheDuration),
	}
}

// yoinks the raw data and expiry time to send to the requester
func (cache *cacheWrapper) yoink(path string) ([]byte, string) {
	cache.RLock()
	defer cache.RUnlock()

	return cache.pages[path].raw, cache.pages[path].expires.Format(time.RFC1123)
}