refactor(response): use strict Accept-Encoding parser
This commit is contained in:
@@ -133,12 +133,16 @@ func (b *Builder) writeHeaders() {
|
||||
b.w.WriteHeader(b.statusCode)
|
||||
}
|
||||
|
||||
// values should be in sync with [Builder.compress] switch/case.
|
||||
var acceptEncoding = AcceptEncoding("br", "gzip", "deflate")
|
||||
|
||||
func (b *Builder) compress(data []byte) {
|
||||
if b.enableCompression && len(data) > compressionThreshold {
|
||||
b.headers.Set("Vary", "Accept-Encoding")
|
||||
acceptEncoding := b.r.Header.Get("Accept-Encoding")
|
||||
switch {
|
||||
case strings.Contains(acceptEncoding, "br"):
|
||||
|
||||
encoding := acceptEncoding.Parse(b.r.Header.Get("Accept-Encoding"))
|
||||
switch encoding {
|
||||
case "br":
|
||||
b.headers.Set("Content-Encoding", "br")
|
||||
b.writeHeaders()
|
||||
|
||||
@@ -146,7 +150,7 @@ func (b *Builder) compress(data []byte) {
|
||||
brotliWriter.Write(data)
|
||||
brotliWriter.Close()
|
||||
return
|
||||
case strings.Contains(acceptEncoding, "gzip"):
|
||||
case "gzip":
|
||||
b.headers.Set("Content-Encoding", "gzip")
|
||||
b.writeHeaders()
|
||||
|
||||
@@ -154,7 +158,7 @@ func (b *Builder) compress(data []byte) {
|
||||
gzipWriter.Write(data)
|
||||
gzipWriter.Close()
|
||||
return
|
||||
case strings.Contains(acceptEncoding, "deflate"):
|
||||
case "deflate":
|
||||
b.headers.Set("Content-Encoding", "deflate")
|
||||
b.writeHeaders()
|
||||
|
||||
|
||||
@@ -358,7 +358,7 @@ func TestIfNoneMatch(t *testing.T) {
|
||||
func TestBuildResponseWithBrotliCompression(t *testing.T) {
|
||||
body := strings.Repeat("a", compressionThreshold+1)
|
||||
r, err := http.NewRequest("GET", "/", nil)
|
||||
r.Header.Set("Accept-Encoding", "gzip, deflate, br")
|
||||
r.Header.Set("Accept-Encoding", "br, gzip, deflate")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user