Enha: gziped css and js
This commit is contained in:
BIN
assets/helpers.js.gz
Normal file
BIN
assets/helpers.js.gz
Normal file
Binary file not shown.
BIN
assets/htmx.min.js.gz
Normal file
BIN
assets/htmx.min.js.gz
Normal file
Binary file not shown.
BIN
assets/htmx.sse.js.gz
Normal file
BIN
assets/htmx.sse.js.gz
Normal file
Binary file not shown.
BIN
assets/output.css.gz
Normal file
BIN
assets/output.css.gz
Normal file
Binary file not shown.
BIN
assets/style.css.gz
Normal file
BIN
assets/style.css.gz
Normal file
Binary file not shown.
BIN
assets/tailwind.css.gz
Normal file
BIN
assets/tailwind.css.gz
Normal file
Binary file not shown.
39
main.go
39
main.go
@ -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)
|
||||
|
Reference in New Issue
Block a user