From bf09d3c0bed8a499eafb8deab0b1214169e6bbb1 Mon Sep 17 00:00:00 2001 From: Las Zenow Date: Mon, 27 Apr 2015 20:15:42 -0400 Subject: [PATCH] Add cache header For now we only add it to images/js/css and not for html/json/xml generated pages. --- config.go | 1 + stats.go | 1 + trantor.go | 29 +++++++++++++++++++++++------ 3 files changed, 25 insertions(+), 6 deletions(-) diff --git a/config.go b/config.go index 2fd74f7..513c4b2 100644 --- a/config.go +++ b/config.go @@ -26,6 +26,7 @@ const ( NEW_ITEMS_PAGE = 50 NUM_NEWS = 10 DAYS_NEWS_INDEXPAGE = 15 + CACHE_MAX_AGE = 1800 STORE_PATH = "store/" TEMPLATE_PATH = "templates/" diff --git a/stats.go b/stats.go index cddf487..25b3d8e 100644 --- a/stats.go +++ b/stats.go @@ -53,6 +53,7 @@ func (sg StatsGatherer) Gather(function func(handler)) func(http.ResponseWriter, h.w = w h.r = r h.sess = GetSession(r, h.db) + function(h) sg.channel <- statsRequest{time.Now(), mux.Vars(r), h.sess, r} diff --git a/trantor.go b/trantor.go index 97215fb..c49a470 100644 --- a/trantor.go +++ b/trantor.go @@ -3,6 +3,7 @@ package main import ( log "github.com/cihub/seelog" + "fmt" "io" "net/http" "os" @@ -220,11 +221,27 @@ func initRouter(db *database.DB, sg *StatsGatherer) { r.HandleFunc("/news/edit", sg.Gather(editNewsHandler)).Methods("GET") r.HandleFunc("/news/edit", sg.Gather(postNewsHandler)).Methods("POST") - h := http.FileServer(http.Dir(IMG_PATH)) - r.Handle("/img/{img}", http.StripPrefix("/img/", h)) - h = http.FileServer(http.Dir(CSS_PATH)) - r.Handle("/css/{css}", http.StripPrefix("/css/", h)) - h = http.FileServer(http.Dir(JS_PATH)) - r.Handle("/js/{js}", http.StripPrefix("/js/", h)) + r.HandleFunc("/img/{img}", fileServer(IMG_PATH, "/img/")) + r.HandleFunc("/css/{css}", fileServer(CSS_PATH, "/css/")) + r.HandleFunc("/js/{js}", fileServer(JS_PATH, "/js/")) http.Handle("/", r) } + +func fileServer(path string, prefix string) func(w http.ResponseWriter, r *http.Request) { + // FIXME: is there a cleaner way without handler? + h := http.FileServer(http.Dir(path)) + handler := http.StripPrefix(prefix, h) + return func(w http.ResponseWriter, r *http.Request) { + addCacheControlHeader(w, false) + handler.ServeHTTP(w, r) + } +} + +func addCacheControlHeader(w http.ResponseWriter, private bool) { + // FIXME: cache of download and cover don't depends on user login + if private { + w.Header().Set("Cache-Control", fmt.Sprintf("max-age=%d, private", CACHE_MAX_AGE)) + } else { + w.Header().Set("Cache-Control", fmt.Sprintf("max-age=%d, public", CACHE_MAX_AGE)) + } +}