Philipp Schrader | 5562df7 | 2022-02-16 20:56:51 -0800 | [diff] [blame] | 1 | package static |
| 2 | |
| 3 | // A year agnostic way to serve static http files. |
| 4 | import ( |
| 5 | "net/http" |
Alex Perry | b2f7652 | 2022-03-30 21:02:05 -0700 | [diff] [blame^] | 6 | "time" |
Philipp Schrader | 5562df7 | 2022-02-16 20:56:51 -0800 | [diff] [blame] | 7 | |
| 8 | "github.com/frc971/971-Robot-Code/scouting/webserver/server" |
| 9 | ) |
| 10 | |
Alex Perry | b2f7652 | 2022-03-30 21:02:05 -0700 | [diff] [blame^] | 11 | // 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. |
| 14 | var epoch = time.Unix(0, 0).Format(time.RFC1123) |
| 15 | |
| 16 | var 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 | |
| 23 | func 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 Schrader | 5562df7 | 2022-02-16 20:56:51 -0800 | [diff] [blame] | 35 | // Serve pages given a port, directory to serve from, and an channel to pass the errors back to the caller. |
| 36 | func ServePages(scoutingServer server.ScoutingServer, directory string) { |
| 37 | // Serve the / endpoint given a folder of pages. |
Alex Perry | b2f7652 | 2022-03-30 21:02:05 -0700 | [diff] [blame^] | 38 | scoutingServer.Handle("/", NoCache(http.FileServer(http.Dir(directory)))) |
Philipp Schrader | 5562df7 | 2022-02-16 20:56:51 -0800 | [diff] [blame] | 39 | } |