diff options
| author | Xe <me@christine.website> | 2022-09-03 15:09:14 +0000 |
|---|---|---|
| committer | Xe <me@christine.website> | 2022-09-03 15:09:19 +0000 |
| commit | 143e320398c509c868fc31cae5dfe628fb5b29d2 (patch) | |
| tree | 3ed55759892cfc0560de244ccb1d58d9fbd6172f /cmd/xedn/main.go | |
| parent | eceb8af2f9b78a00911fd3c744ac9b09b7ec614e (diff) | |
| download | x-143e320398c509c868fc31cae5dfe628fb5b29d2.tar.xz x-143e320398c509c868fc31cae5dfe628fb5b29d2.zip | |
cmd/xedn: aha that's how caching works
Signed-off-by: Xe <me@christine.website>
Diffstat (limited to 'cmd/xedn/main.go')
| -rw-r--r-- | cmd/xedn/main.go | 30 |
1 files changed, 30 insertions, 0 deletions
diff --git a/cmd/xedn/main.go b/cmd/xedn/main.go index 2feae65..5c8b540 100644 --- a/cmd/xedn/main.go +++ b/cmd/xedn/main.go @@ -12,6 +12,7 @@ import ( "log" "net/http" "os" + "sync" "time" "github.com/golang/groupcache" @@ -51,6 +52,16 @@ var Group = groupcache.NewGroup("b2-bucket", cacheSize, groupcache.GetterFunc( return web.NewError(http.StatusOK, resp) } + etag := fmt.Sprintf("%q", resp.Header.Get("x-bz-content-sha1")) + resp.Header.Set("ETag", etag) + etagLock.Lock() + etags[key] = etag + etagLock.Unlock() + + // cache control headers + resp.Header.Set("Cache-Control", "max-age:604800") + resp.Header.Set("Expires", time.Now().Add(604800 * time.Second).Format(http.TimeFormat)) + body, err := io.ReadAll(resp.Body) if err != nil { return fmt.Errorf("can't read from b2: %v", err) @@ -78,8 +89,17 @@ var ( cacheHits = expvar.NewInt("cache_hits") cacheErrors = expvar.NewInt("cache_errors") cacheLoads = expvar.NewInt("cache_loads") + + etagMatches = expvar.NewInt("etag_matches") + + etags map[string]string + etagLock sync.RWMutex ) +func init() { + etags = map[string]string{} +} + func refreshMetrics () { t := time.NewTicker(10 * time.Second) defer t.Stop() @@ -125,6 +145,16 @@ func main() { mux := http.NewServeMux() mux.HandleFunc("/.within/metrics", tsweb.VarzHandler) mux.HandleFunc("/file/christine-static/", func(w http.ResponseWriter, r *http.Request) { + etagLock.RLock() + etag, ok := etags[r.URL.Path] + etagLock.RUnlock() + + if r.Header.Get("If-None-Match") == etag && ok { + etagMatches.Add(1) + w.WriteHeader(http.StatusNotModified) + return + } + var b []byte err := Group.Get(nil, r.URL.Path, groupcache.AllocatingByteSliceSink(&b)) if err != nil { |
