54
internal/httpapp/compression_middleware.go
Normal file
54
internal/httpapp/compression_middleware.go
Normal 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)
|
||||
}
|
||||
Reference in New Issue
Block a user