Browse Source

Correctly set Content-Length header (#11)

* Correctly set Content-Length header

Set Content-Length to be the number of bytes written to the Writer rather than zero.

* Expect Content-Length to be non-zero when running tests

* Add a test to verify that response size and Content-Length are equal
Łukasz Mierzwa 8 years ago
parent
commit
ff223ab9f8
2 changed files with 5 additions and 2 deletions
  1. 2 1
      gzip.go
  2. 3 1
      gzip_test.go

+ 2 - 1
gzip.go

@@ -2,6 +2,7 @@ package gzip
 
 
 import (
 import (
 	"compress/gzip"
 	"compress/gzip"
+	"fmt"
 	"io/ioutil"
 	"io/ioutil"
 	"net/http"
 	"net/http"
 	"path/filepath"
 	"path/filepath"
@@ -40,8 +41,8 @@ func Gzip(level int) gin.HandlerFunc {
 		c.Header("Vary", "Accept-Encoding")
 		c.Header("Vary", "Accept-Encoding")
 		c.Writer = &gzipWriter{c.Writer, gz}
 		c.Writer = &gzipWriter{c.Writer, gz}
 		defer func() {
 		defer func() {
-			c.Header("Content-Length", "0")
 			gz.Close()
 			gz.Close()
+			c.Header("Content-Length", fmt.Sprint(c.Writer.Size()))
 		}()
 		}()
 		c.Next()
 		c.Next()
 	}
 	}

+ 3 - 1
gzip_test.go

@@ -2,6 +2,7 @@ package gzip
 
 
 import (
 import (
 	"compress/gzip"
 	"compress/gzip"
+	"fmt"
 	"io/ioutil"
 	"io/ioutil"
 	"net/http"
 	"net/http"
 	"net/http/httptest"
 	"net/http/httptest"
@@ -37,8 +38,9 @@ func TestGzip(t *testing.T) {
 	assert.Equal(t, w.Code, 200)
 	assert.Equal(t, w.Code, 200)
 	assert.Equal(t, w.Header().Get("Content-Encoding"), "gzip")
 	assert.Equal(t, w.Header().Get("Content-Encoding"), "gzip")
 	assert.Equal(t, w.Header().Get("Vary"), "Accept-Encoding")
 	assert.Equal(t, w.Header().Get("Vary"), "Accept-Encoding")
-	assert.Equal(t, w.Header().Get("Content-Length"), "0")
+	assert.NotEqual(t, w.Header().Get("Content-Length"), "0")
 	assert.NotEqual(t, w.Body.Len(), 19)
 	assert.NotEqual(t, w.Body.Len(), 19)
+	assert.Equal(t, fmt.Sprint(w.Body.Len()), w.Header().Get("Content-Length"))
 
 
 	gr, err := gzip.NewReader(w.Body)
 	gr, err := gzip.NewReader(w.Body)
 	assert.NoError(t, err)
 	assert.NoError(t, err)