p14
Some checks failed
CI / test-build (push) Failing after 1m11s

This commit is contained in:
2025-12-15 00:53:35 +07:00
parent df475bc85e
commit 96a6b5a4cf
4 changed files with 339 additions and 20 deletions

View File

@@ -0,0 +1,54 @@
package httpapp
import (
"compress/gzip"
"io"
"net/http"
"strings"
)
// compressionMiddleware provides gzip compression for responses
func (a *App) compressionMiddleware(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
// Check if client accepts gzip
if !strings.Contains(r.Header.Get("Accept-Encoding"), "gzip") {
next.ServeHTTP(w, r)
return
}
// Skip compression for certain content types
contentType := r.Header.Get("Content-Type")
if strings.HasPrefix(contentType, "image/") ||
strings.HasPrefix(contentType, "video/") ||
strings.HasPrefix(contentType, "application/zip") {
next.ServeHTTP(w, r)
return
}
// Create gzip writer
gz := gzip.NewWriter(w)
defer gz.Close()
// Set headers
w.Header().Set("Content-Encoding", "gzip")
w.Header().Set("Vary", "Accept-Encoding")
// Wrap response writer
gzw := &gzipResponseWriter{
ResponseWriter: w,
Writer: gz,
}
next.ServeHTTP(gzw, r)
})
}
// gzipResponseWriter wraps http.ResponseWriter with gzip compression
type gzipResponseWriter struct {
http.ResponseWriter
Writer io.Writer
}
func (gzw *gzipResponseWriter) Write(b []byte) (int, error) {
return gzw.Writer.Write(b)
}