From fb984c2b71fa74f0c13b81cd1cabf01e81f3ddf6 Mon Sep 17 00:00:00 2001 From: Will Norris Date: Tue, 14 Nov 2023 15:00:46 -0800 Subject: [PATCH] client/web: server /index.html on 404 requests In production, the asset handler is receiving requests for pages like /details, which results in a 404. Instead, if we know the requested file does not exist, serve the main index page and let wouter route it appropriately on the frontend. Updates tailscale/corp/#14335 Signed-off-by: Will Norris --- client/web/assets.go | 15 ++++++++++++++- 1 file changed, 14 insertions(+), 1 deletion(-) diff --git a/client/web/assets.go b/client/web/assets.go index c4af0694b..ccef6a0e1 100644 --- a/client/web/assets.go +++ b/client/web/assets.go @@ -4,6 +4,7 @@ package web import ( + "io/fs" "log" "net/http" "net/http/httputil" @@ -22,7 +23,19 @@ func assetsHandler(devMode bool) (_ http.Handler, cleanup func()) { cleanup := startDevServer() return devServerProxy(), cleanup } - return http.FileServer(http.FS(prebuilt.FS())), nil + + fsys := prebuilt.FS() + fileserver := http.FileServer(http.FS(fsys)) + return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + _, err := fs.Stat(fsys, strings.TrimPrefix(r.URL.Path, "/")) + if os.IsNotExist(err) { + // rewrite request to just fetch /index.html and let + // the frontend router handle it. + r = r.Clone(r.Context()) + r.URL.Path = "/" + } + fileserver.ServeHTTP(w, r) + }), nil } // startDevServer starts the JS dev server that does on-demand rebuilding