From 523b199997e3442d65a437cb2a31804159cfa999 Mon Sep 17 00:00:00 2001 From: Jan-Lukas Else Date: Mon, 8 Apr 2019 13:58:41 +0200 Subject: [PATCH] Don't serve every static file --- main.go | 32 ++++++++++++----------- static/chart.html | 2 +- static/generator.html | 59 ------------------------------------------- static/test.html | 11 -------- 4 files changed, 18 insertions(+), 86 deletions(-) delete mode 100644 static/generator.html delete mode 100644 static/test.html diff --git a/main.go b/main.go index 3525157..0ce8338 100644 --- a/main.go +++ b/main.go @@ -17,7 +17,6 @@ type kis3 struct { db *Database router *mux.Router staticBox *packr.Box - staticFS http.Handler } var ( @@ -31,7 +30,6 @@ func init() { } setupRouter() app.staticBox = packr.New("staticFiles", "./static") - app.staticFS = http.FileServer(app.staticBox) } func main() { @@ -56,7 +54,8 @@ func setupRouter() { staticRouter := app.router.PathPrefix("").Subrouter() staticRouter.Use(corsHandler) - staticRouter.PathPrefix("").Handler(http.HandlerFunc(serveStaticFile)) + staticRouter.HandleFunc("/kis3.js", serveTrackingScript) + staticRouter.PathPrefix("").Handler(http.HandlerFunc(sendHelloResponse)) } func startListening() { @@ -76,17 +75,14 @@ func trackView(w http.ResponseWriter, r *http.Request) { } } -func sendHelloResponse(w http.ResponseWriter) { +func sendHelloResponse(w http.ResponseWriter, _ *http.Request) { _, _ = fmt.Fprint(w, "Hello from KISSS") } -func serveStaticFile(w http.ResponseWriter, r *http.Request) { - uPath := r.URL.Path - if uPath != "/" && app.staticBox.Has(uPath) { - app.staticFS.ServeHTTP(w, r) - } else { - sendHelloResponse(w) - } +func serveTrackingScript(w http.ResponseWriter, _ *http.Request) { + w.Header().Add("Content-Type", "application/javascript") + trackingScriptBytes, _ := app.staticBox.Find("kis3.js") + _, _ = w.Write(trackingScriptBytes) } func requestStats(w http.ResponseWriter, r *http.Request) { @@ -159,12 +155,18 @@ func sendChartResponse(result []*RequestResultRow, w http.ResponseWriter) { labels[i] = row.First values[i] = row.Second } + chartJSString, e := app.staticBox.FindString("Chart.min.js") + if e != nil { + return + } data := struct { - Labels []string - Values []int + Labels []string + Values []int + ChartJS template.JS }{ - Labels: labels, - Values: values, + Labels: labels, + Values: values, + ChartJS: template.JS(chartJSString), } chartTemplateString, e := app.staticBox.FindString("chart.html") if e != nil { diff --git a/static/chart.html b/static/chart.html index 48add39..75f8da6 100644 --- a/static/chart.html +++ b/static/chart.html @@ -3,7 +3,7 @@ KISSS - +