blob: 57824d98f0e9fac04e3f1983bac8421a388fc052 [file] [log] [blame]
Philipp Schrader5562df72022-02-16 20:56:51 -08001package static
2
3// A year agnostic way to serve static http files.
4import (
5 "net/http"
Alex Perryb2f76522022-03-30 21:02:05 -07006 "time"
Philipp Schrader5562df72022-02-16 20:56:51 -08007
8 "github.com/frc971/971-Robot-Code/scouting/webserver/server"
9)
10
Alex Perryb2f76522022-03-30 21:02:05 -070011// We want the static files (which include JS that is modified over time), to not be cached.
12// This ensures users get updated versions when uploaded to the server.
13// Based on https://stackoverflow.com/a/33881296, this disables cache for most browsers.
14var epoch = time.Unix(0, 0).Format(time.RFC1123)
15
16var noCacheHeaders = map[string]string{
17 "Expires": epoch,
18 "Cache-Control": "no-cache, private, max-age=0",
19 "Pragma": "no-cache",
20 "X-Accel-Expires": "0",
21}
22
23func NoCache(h http.Handler) http.Handler {
24 fn := func(w http.ResponseWriter, r *http.Request) {
25 for k, v := range noCacheHeaders {
26 w.Header().Set(k, v)
27 }
28
29 h.ServeHTTP(w, r)
30 }
31
32 return http.HandlerFunc(fn)
33}
34
Philipp Schrader5562df72022-02-16 20:56:51 -080035// Serve pages given a port, directory to serve from, and an channel to pass the errors back to the caller.
36func ServePages(scoutingServer server.ScoutingServer, directory string) {
37 // Serve the / endpoint given a folder of pages.
Alex Perryb2f76522022-03-30 21:02:05 -070038 scoutingServer.Handle("/", NoCache(http.FileServer(http.Dir(directory))))
Philipp Schrader5562df72022-02-16 20:56:51 -080039}