Skip to content

Commit

Permalink
fix: add br compressor for default config
Browse files Browse the repository at this point in the history
  • Loading branch information
vicanso committed Jun 12, 2019
1 parent 7b79386 commit fb6e1c8
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 8 deletions.
16 changes: 11 additions & 5 deletions compress.go
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ var (
)

const (
defaultCompresMinLength = 1024
defaultCompressMinLength = 1024
)

type (
Expand Down Expand Up @@ -75,7 +75,8 @@ func NewWithDefaultCompressor(config Config) cod.Handler {
// 添加默认的 brotli 压缩
br := new(BrCompressor)
_, err := br.Compress([]byte("brotli"), 0)
if err != nil {
// 如果可以压缩成功,则添加 br 压缩
if err == nil {
compressorList = append(compressorList, br)
}

Expand All @@ -90,7 +91,7 @@ func NewWithDefaultCompressor(config Config) cod.Handler {
func New(config Config) cod.Handler {
minLength := config.MinLength
if minLength == 0 {
minLength = defaultCompresMinLength
minLength = defaultCompressMinLength
}
skipper := config.Skipper
if skipper == nil {
Expand Down Expand Up @@ -130,7 +131,7 @@ func New(config Config) cod.Handler {
body = c.BodyBuffer.Bytes()
}
if !isReaderBody {
// 如果数据长度少于最小压缩长度或
// 如果数据长度少于最小压缩长度
if len(body) < minLength {
return
}
Expand All @@ -143,9 +144,14 @@ func New(config Config) cod.Handler {
}
if isReaderBody {
c.SetHeader(cod.HeaderContentEncoding, encoding)
err = compressor.Pipe(c, config.Level)
if err != nil {
return
}
// pipe 将数据直接转至原有的Response,因此设置committed为true
c.Committed = true
compressor.Pipe(c, config.Level)
// 清除 reader body
c.Body = nil
} else {
newBuf, e := compressor.Compress(body, config.Level)
// 如果压缩成功,则使用压缩数据
Expand Down
7 changes: 4 additions & 3 deletions compress_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import (
"fmt"
"math/rand"
"net/http/httptest"
"os"
"testing"
"time"

Expand Down Expand Up @@ -157,6 +158,7 @@ func TestCompress(t *testing.T) {
}
body := bytes.NewBufferString("abcd")
c.BodyBuffer = body
c.SetHeader(cod.HeaderContentType, "text/plain")
err := fn(c)
assert.Nil(err)
assert.Equal(c.BodyBuffer.Bytes(), body.Bytes())
Expand Down Expand Up @@ -244,7 +246,6 @@ func TestCompress(t *testing.T) {
return nil
}
body := bytes.NewBufferString(randomString(4096))
fmt.Println(len(body.Bytes()))
gzipBytes, _ := doGzip(body.Bytes(), 0)
c.Body = body
err := fn(c)
Expand All @@ -264,10 +265,10 @@ func TestMain(m *testing.M) {
// and CoverMode will be non empty if run with -cover
if rc == 0 && testing.CoverMode() != "" {
c := testing.Coverage()
if c < 0.9 {
if c < 0.85 {
fmt.Println("Tests passed but coverage failed at", c)
rc = -1
}
}
// os.Exit(rc)
os.Exit(rc)
}

0 comments on commit fb6e1c8

Please sign in to comment.