Enha: gziped css and js

This commit is contained in:
Grail Finder
2025-07-10 09:48:12 +03:00
parent a9c9837b7c
commit d4c57c3262
7 changed files with 37 additions and 2 deletions

BIN
assets/helpers.js.gz Normal file

Binary file not shown.

BIN
assets/htmx.min.js.gz Normal file

Binary file not shown.

BIN
assets/htmx.sse.js.gz Normal file

Binary file not shown.

BIN
assets/output.css.gz Normal file

Binary file not shown.

BIN
assets/style.css.gz Normal file

Binary file not shown.

BIN
assets/tailwind.css.gz Normal file

Binary file not shown.

39
main.go
View File

@ -10,6 +10,8 @@ import (
"net/http"
"os"
"os/signal"
"path/filepath"
"strings"
"syscall"
"time"
)
@ -20,6 +22,38 @@ func init() {
cfg = config.LoadConfigOrDefault("")
}
// GzipFileServer serves pre-compressed .gz files if available
func GzipFileServer(root http.FileSystem) http.Handler {
fs := http.FileServer(root)
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
// Check if client accepts gzip
if strings.Contains(r.Header.Get("Accept-Encoding"), "gzip") {
// Check for .gz version of the file
gzPath := r.URL.Path + ".gz"
if file, err := root.Open(gzPath); err == nil {
file.Close()
// Set headers for gzip
w.Header().Set("Content-Encoding", "gzip")
w.Header().Set("Content-Type", getContentType(r.URL.Path))
r.URL.Path = gzPath
}
}
fs.ServeHTTP(w, r)
})
}
// Helper to set correct Content-Type
func getContentType(path string) string {
switch filepath.Ext(path) {
case ".css":
return "text/css"
case ".js":
return "application/javascript"
default:
return "" // http.FileServer will detect it
}
}
func ListenToRequests(port string) *http.Server {
mux := http.NewServeMux()
server := &http.Server{
@ -28,8 +62,9 @@ func ListenToRequests(port string) *http.Server {
// ReadTimeout: time.Second * 5, // does this timeout conflict with sse connection?
WriteTimeout: 0, // sse streaming
}
fs := http.FileServer(http.Dir("assets/"))
mux.Handle("GET /assets/", http.StripPrefix("/assets/", fs))
// fs := http.FileServer(http.Dir("assets/"))
fs := http.Dir("assets/")
mux.Handle("GET /assets/", http.StripPrefix("/assets/", GzipFileServer(fs)))
//
mux.HandleFunc("GET /ping", handlers.HandlePing)
mux.HandleFunc("GET /", handlers.HandleHome)