diff options
author | Steve Manuel <nilslice@gmail.com> | 2016-12-06 17:56:39 -0800 |
---|---|---|
committer | Steve Manuel <nilslice@gmail.com> | 2016-12-06 17:56:39 -0800 |
commit | 70a841287e6f740b09ac29d2f6266281509a3163 (patch) | |
tree | b83f321091dc23b83914614ac401a3beb5f45857 /system/db/cache.go | |
parent | f2fc4db1ea0dbf4a1f75fb3e52b64e6f529e5e44 (diff) |
tracking new file
Diffstat (limited to 'system/db/cache.go')
-rw-r--r-- | system/db/cache.go | 75 |
1 files changed, 75 insertions, 0 deletions
diff --git a/system/db/cache.go b/system/db/cache.go new file mode 100644 index 0000000..93cd3a6 --- /dev/null +++ b/system/db/cache.go @@ -0,0 +1,75 @@ +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, must-revalidate, proxy-revalidate", 60*60*24*30) + res.Header().Add("Etag", etag) + res.Header().Add("Cache-Control", policy) + + if match := res.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() + + var data 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 { + data.Add(k, vv[i]) + } + } + } + + err = SetConfig(data) + if err != nil { + + } + + return nil +} |