package platform import ( "compress/gzip" "io" "mime" "net/http" "strconv" "strings" "sync" "github.com/gin-gonic/gin" ) // compressMin is the smallest body worth compressing, for responses that // state their length. const compressMin = 1024 var gzipWriters = sync.Pool{New: func() any { w, _ := gzip.NewWriterLevel(io.Discard, gzip.DefaultCompression) return w }} // Compress gzips text responses (HTML, CSS, JavaScript, JSON, XML, SVG) for // clients that accept it. Status pages list thousands of components in // markup that repeats itself, so this shrinks them many times over. func Compress() gin.HandlerFunc { return func(c *gin.Context) { c.Writer.Header().Add("Vary", "Accept-Encoding") if c.Request.Method == http.MethodHead || !acceptsGzip(c.Request.Header.Get("Accept-Encoding")) { c.Next() return } w := &gzipWriter{ResponseWriter: c.Writer} c.Writer = w defer w.finish() c.Next() } } // acceptsGzip reports whether an Accept-Encoding header allows gzip. func acceptsGzip(header string) bool { for _, part := range strings.Split(header, ",") { name, params, _ := strings.Cut(part, ";") name = strings.ToLower(strings.TrimSpace(name)) if name != "gzip" && name != "*" { continue } for _, p := range strings.Split(params, ";") { k, v, _ := strings.Cut(strings.TrimSpace(p), "=") if strings.EqualFold(k, "q") { if q, err := strconv.ParseFloat(strings.TrimSpace(v), 64); err == nil && q == 0 { return false } } } return true } return false } func compressible(contentType string) bool { mt, _, err := mime.ParseMediaType(contentType) if err != nil { return false } switch { case strings.HasPrefix(mt, "text/"): return true case mt == "application/json", mt == "application/javascript", mt == "image/svg+xml", mt == "application/xml", mt == "application/rss+xml", mt == "application/atom+xml": return true } return strings.HasSuffix(mt, "+json") || strings.HasSuffix(mt, "+xml") } // gzipWriter decides at the first write whether to compress, when the // handler has set the status and headers. type gzipWriter struct { gin.ResponseWriter decided bool gz *gzip.Writer } func (w *gzipWriter) decide() { w.decided = true h := w.Header() switch status := w.Status(); { case status < 200, status == http.StatusNoContent, status == http.StatusNotModified, status == http.StatusPartialContent: return } if h.Get("Content-Encoding") != "" || !compressible(h.Get("Content-Type")) { return } if n, err := strconv.Atoi(h.Get("Content-Length")); err == nil && n < compressMin { return } h.Set("Content-Encoding", "gzip") h.Del("Content-Length") if etag := h.Get("ETag"); etag != "" && !strings.HasPrefix(etag, "W/") { h.Set("ETag", "W/"+etag) } w.gz = gzipWriters.Get().(*gzip.Writer) w.gz.Reset(w.ResponseWriter) } // Write compresses b if decide chose to, which it does at the first write. func (w *gzipWriter) Write(b []byte) (int, error) { if !w.decided { if w.Header().Get("Content-Type") == "" { w.Header().Set("Content-Type", http.DetectContentType(b)) } w.decide() } if w.gz == nil { return w.ResponseWriter.Write(b) } return w.gz.Write(b) } // WriteString writes s like Write, so strings are compressed as well. func (w *gzipWriter) WriteString(s string) (int, error) { return w.Write([]byte(s)) } // Flush sends what is compressed so far, for responses that stream. func (w *gzipWriter) Flush() { if w.gz != nil { _ = w.gz.Flush() } w.ResponseWriter.Flush() } func (w *gzipWriter) finish() { if w.gz == nil { return } _ = w.gz.Close() w.gz.Reset(io.Discard) gzipWriters.Put(w.gz) w.gz = nil }