Files
Thomas Nilles 6f508ed194 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.
2026-01-13 00:14:28 -05:00

48 lines
1.2 KiB
Go

package main
import (
"net/http"
"strings"
"github.com/go-chi/chi/v5"
"github.com/go-chi/chi/v5/middleware"
)
func main() {
// Create a new router
r := chi.NewRouter()
// Add some middleware for logging and recover
r.Use(middleware.Logger)
r.Use(middleware.Recoverer)
// Register the hello world handler at the root path
// 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)
}
// FileServer sets up a http.FileServer handler for serving static files.
func FileServer(r chi.Router, publicPath string, root http.FileSystem) {
if publicPath == "" {
publicPath = "/"
}
// Ensure the path ends with a slash
if publicPath[len(publicPath)-1] != '/' {
publicPath += "/"
}
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)
}))
}