From f85ecd166593e70b80e03eeb9097593dc978c722 Mon Sep 17 00:00:00 2001 From: happysnaker <73147033+happysnaker@users.noreply.github.com> Date: Thu, 2 Jul 2026 04:21:41 +0800 Subject: [PATCH] fix(middleware): honor all-types compress wildcard --- middleware/compress.go | 3 +++ middleware/compress_test.go | 47 +++++++++++++++++++++++++++++++++++++ 2 files changed, 50 insertions(+) diff --git a/middleware/compress.go b/middleware/compress.go index 4e46f70a..2996f01e 100644 --- a/middleware/compress.go +++ b/middleware/compress.go @@ -281,6 +281,9 @@ func (cw *compressResponseWriter) isCompressible() bool { return true } if contentType, _, hadSlash := strings.Cut(contentType, "/"); hadSlash { + if _, ok := cw.contentWildcards[""]; ok { + return true + } _, ok := cw.contentWildcards[contentType] return ok } diff --git a/middleware/compress_test.go b/middleware/compress_test.go index 028343c8..941f9650 100644 --- a/middleware/compress_test.go +++ b/middleware/compress_test.go @@ -169,6 +169,53 @@ func TestCompressorWildcards(t *testing.T) { } } +func TestCompressorWildcardAllTypes(t *testing.T) { + r := chi.NewRouter() + r.Use(NewCompressor(5, "/*").Handler) + + r.Get("/json", func(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Content-Type", "application/json") + w.Write([]byte(`{"ok":true}`)) + }) + + r.Get("/html", func(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Content-Type", "text/html; charset=utf-8") + w.Write([]byte("

ok

")) + }) + + ts := httptest.NewServer(r) + defer ts.Close() + + tests := []struct { + name string + path string + body string + }{ + { + name: "application type matches all wildcard", + path: "/json", + body: `{"ok":true}`, + }, + { + name: "text type matches all wildcard", + path: "/html", + body: "

ok

", + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + resp, body := testRequestWithAcceptedEncodings(t, ts, http.MethodGet, tt.path, "gzip") + if got := resp.Header.Get("Content-Encoding"); got != "gzip" { + t.Fatalf("expected gzip encoding, got %q", got) + } + if body != tt.body { + t.Fatalf("expected body %q, got %q", tt.body, body) + } + }) + } +} + func testRequestWithAcceptedEncodings(t *testing.T, ts *httptest.Server, method, path string, encodings ...string) (*http.Response, string) { req, err := http.NewRequest(method, ts.URL+path, nil) if err != nil {