Serve static files at /static and set JS MIME type
Add strings import for .js detection. Register an additional FileServer at "/static/" to expose static files under that prefix. In the FileServer handler, set Content-Type to "application/javascript" for .js requests.
This commit is contained in:
@@ -2,6 +2,7 @@ package main
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"strings"
|
||||
|
||||
"github.com/go-chi/chi/v5"
|
||||
"github.com/go-chi/chi/v5/middleware"
|
||||
@@ -17,9 +18,10 @@ func main() {
|
||||
|
||||
// Register the hello world handler at the root path
|
||||
|
||||
// Serve static HTML files from the "static" directory
|
||||
// (e.g., /static/index.html will be accessible at /static/index.html)
|
||||
// Serve static HTML files from the "static" directory at the root
|
||||
FileServer(r, "/", http.Dir("./static"))
|
||||
// Also serve the same files under the "/static" URL prefix
|
||||
FileServer(r, "/static/", http.Dir("./static"))
|
||||
|
||||
// Start the HTTP server
|
||||
http.ListenAndServe(":8080", r)
|
||||
@@ -36,6 +38,10 @@ func FileServer(r chi.Router, publicPath string, root http.FileSystem) {
|
||||
}
|
||||
fs := http.StripPrefix(publicPath, http.FileServer(root))
|
||||
r.Get(publicPath+"*", http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
// Set correct MIME type for JavaScript files
|
||||
if strings.HasSuffix(r.URL.Path, ".js") {
|
||||
w.Header().Set("Content-Type", "application/javascript")
|
||||
}
|
||||
fs.ServeHTTP(w, r)
|
||||
}))
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user