Skip to content

Commit

Permalink
Merge pull request #8 from ivov/fix-static-file-serving
Browse files Browse the repository at this point in the history
fix: Correct static file serving
  • Loading branch information
ivov authored Nov 23, 2024
2 parents c1e45bb + fcb2a95 commit 2515509
Showing 1 changed file with 35 additions and 7 deletions.
42 changes: 35 additions & 7 deletions internal/api/api.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ package api
import (
"expvar"
"net/http"
"strings"
"sync"

"github.com/ivov/n8n-shortlink/internal"
Expand All @@ -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

Expand All @@ -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)
Expand Down

0 comments on commit 2515509

Please sign in to comment.