Skip to content

Commit 2272779

Browse files
jungbumwooshelldandy
authored andcommitted
gzip: escape heap allocation (grafana#3922)
* add benchmark * escape heap alloc * rm bench test result * fix lint: add error checking
1 parent 84a8d6c commit 2272779

File tree

2 files changed

+20
-1
lines changed

2 files changed

+20
-1
lines changed

pkg/util/gziphandler/gzip.go

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -520,15 +520,22 @@ func handleContentType(contentTypes []parsedContentType, ct string) bool {
520520
func parseEncodings(s string) (codings, error) {
521521
c := make(codings)
522522
var e []string
523+
var ss string
524+
var found bool
523525

524-
for _, ss := range strings.Split(s, ",") {
526+
for {
527+
ss, s, found = strings.Cut(s, ",")
525528
coding, qvalue, err := parseCoding(ss)
526529

527530
if err != nil {
528531
e = append(e, err.Error())
529532
} else {
530533
c[coding] = qvalue
531534
}
535+
536+
if !found {
537+
break
538+
}
532539
}
533540

534541
// TODO (adammck): Use a proper multi-error struct, so the individual errors

pkg/util/gziphandler/gzip_test.go

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,7 @@ import (
1515
"net/url"
1616
"os"
1717
"strconv"
18+
"strings"
1819
"testing"
1920

2021
"github.com/stretchr/testify/assert"
@@ -614,6 +615,17 @@ func TestContentTypes(t *testing.T) {
614615
}
615616
}
616617

618+
func BenchmarkParseEncodings(b *testing.B) {
619+
req := httptest.NewRequest(http.MethodGet, "/whatever", nil)
620+
req.Header.Set("Accept-Encoding", strings.Repeat(",", http.DefaultMaxHeaderBytes))
621+
b.ReportAllocs()
622+
b.ResetTimer()
623+
for range b.N {
624+
_, err := parseEncodings(req.Header.Get(acceptEncoding))
625+
assert.Error(b, err)
626+
}
627+
}
628+
617629
// --------------------------------------------------------------------
618630

619631
func BenchmarkGzipHandler_S2k(b *testing.B) { benchmark(b, false, 2048) }

0 commit comments

Comments
 (0)