summaryrefslogtreecommitdiff
path: root/system/db/cache.go
diff options
context:
space:
mode:
authorSteve <nilslice@gmail.com>2016-12-12 00:34:46 -0800
committerGitHub <noreply@github.com>2016-12-12 00:34:46 -0800
commite7c23d71d5179744c230ab4e25f405a5607ba905 (patch)
tree758eba1275e1436220281fd45e3ad642fcda4598 /system/db/cache.go
parentf39c1519ab382a343c05163f00f38c83bff3583d (diff)
parent3b10b345045428b9011eecd0ded9c04db42bf28f (diff)
Merge pull request #20 from bosssauce/ponzu-dev
[core] cache-control & db specifier namespace clean-up
Diffstat (limited to 'system/db/cache.go')
-rw-r--r--system/db/cache.go79
1 files changed, 79 insertions, 0 deletions
diff --git a/system/db/cache.go b/system/db/cache.go
new file mode 100644
index 0000000..5f2dd03
--- /dev/null
+++ b/system/db/cache.go
@@ -0,0 +1,79 @@
+package db
+
+import (
+ "encoding/base64"
+ "encoding/json"
+ "fmt"
+ "net/http"
+ "net/url"
+ "strings"
+ "time"
+)
+
+// CacheControl sets the default cache policy on static asset responses
+func CacheControl(next http.Handler) http.HandlerFunc {
+ return http.HandlerFunc(func(res http.ResponseWriter, req *http.Request) {
+ etag := ConfigCache("etag")
+ policy := fmt.Sprintf("max-age=%d, public", 60*60*24*30)
+ res.Header().Add("ETag", etag)
+ res.Header().Add("Cache-Control", policy)
+
+ if match := req.Header.Get("If-None-Match"); match != "" {
+ if strings.Contains(match, etag) {
+ res.WriteHeader(http.StatusNotModified)
+ return
+ }
+ }
+
+ next.ServeHTTP(res, req)
+ })
+}
+
+// NewEtag generates a new Etag for response caching
+func NewEtag() string {
+ now := fmt.Sprintf("%d", time.Now().Unix())
+ etag := base64.StdEncoding.EncodeToString([]byte(now))
+
+ return etag
+}
+
+// InvalidateCache sets a new Etag for http responses
+func InvalidateCache() error {
+ kv := make(map[string]interface{})
+
+ c, err := ConfigAll()
+ if err != nil {
+ return err
+ }
+
+ err = json.Unmarshal(c, &kv)
+ if err != nil {
+ return err
+ }
+
+ kv["etag"] = NewEtag()
+
+ data := make(url.Values)
+ for k, v := range kv {
+ switch v.(type) {
+ case string:
+ data.Set(k, v.(string))
+ case []string:
+ vv := v.([]string)
+ for i := range vv {
+ if i == 0 {
+ data.Set(k, vv[i])
+ } else {
+ data.Add(k, vv[i])
+ }
+ }
+ }
+ }
+
+ err = SetConfig(data)
+ if err != nil {
+
+ }
+
+ return nil
+}