From fcb2a954c200dfb4b4e17a87116747f715bccad0 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Iv=C3=A1n=20Ovejero?= Date: Sat, 23 Nov 2024 19:35:46 +0100 Subject: [PATCH] fix: Correct static file serving --- internal/api/api.go | 42 +++++++++++++++++++++++++++++++++++------- 1 file changed, 35 insertions(+), 7 deletions(-) diff --git a/internal/api/api.go b/internal/api/api.go index 2265061..3768433 100644 --- a/internal/api/api.go +++ b/internal/api/api.go @@ -3,6 +3,7 @@ package api import ( "expvar" "net/http" + "strings" "sync" "github.com/ivov/n8n-shortlink/internal" @@ -21,14 +22,23 @@ type API struct { VisitService *services.VisitService } +// StaticFileHandler creates a handler serving static files with the correct MIME type +func StaticFileHandler(fileServer http.Handler, contentType string) http.HandlerFunc { + return func(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Content-Type", contentType) + http.StripPrefix("/static/", fileServer).ServeHTTP(w, r) + } +} + // Routes sets up middleware and routes on the API. func (api *API) Routes() http.Handler { r := http.NewServeMux() - static := internal.Static() - fileServer := http.FileServer(http.FS(static)) - r.Handle("GET /static/*", http.StripPrefix("/static", fileServer)) + + r.HandleFunc("GET /", func(w http.ResponseWriter, r *http.Request) { + http.ServeFileFS(w, r, static, "index.html") + }) // /static/canvas.tmpl.html and /static/swagger.html blocked by reverse proxy @@ -42,14 +52,32 @@ func (api *API) Routes() http.Handler { http.ServeFile(w, r, "openapi.yml") }) + r.HandleFunc("GET /static/js/{file}", StaticFileHandler(fileServer, "application/javascript; charset=utf-8")) + r.HandleFunc("GET /static/styles/{file}", StaticFileHandler(fileServer, "text/css; charset=utf-8")) + + r.HandleFunc("GET /static/img/{file}", func(w http.ResponseWriter, r *http.Request) { + contentType := "image/png" // default + switch { + case strings.HasSuffix(r.URL.Path, ".svg"): + contentType = "image/svg+xml" + case strings.HasSuffix(r.URL.Path, ".ico"): + contentType = "image/x-icon" + } + StaticFileHandler(fileServer, contentType)(w, r) + }) + + r.HandleFunc("GET /static/fonts/{file}", func(w http.ResponseWriter, r *http.Request) { + contentType := "font/woff2" // default + if strings.HasSuffix(r.URL.Path, ".ttf") { + contentType = "font/ttf" + } + StaticFileHandler(fileServer, contentType)(w, r) + }) + r.HandleFunc("POST /shortlink", api.HandlePostShortlink) r.HandleFunc("GET /{slug}/view", api.HandleGetSlug) r.HandleFunc("GET /{slug}", api.HandleGetSlug) - r.HandleFunc("GET /", func(w http.ResponseWriter, r *http.Request) { - http.ServeFileFS(w, r, static, "index.html") - }) - mw := api.SetupMiddleware() return mw(r)