From aa59f0c26e3cf95b4570979965c6fcfd4e5ff0ab Mon Sep 17 00:00:00 2001 From: vicanso Date: Mon, 24 Dec 2018 16:42:55 +0800 Subject: [PATCH] refactor: gzip only support for text/javascript/json --- middleware/static_serve.go | 23 ++++++++++++++++++++++- middleware/static_serve_test.go | 19 +++++++++++++++++++ 2 files changed, 41 insertions(+), 1 deletion(-) diff --git a/middleware/static_serve.go b/middleware/static_serve.go index 674a718..c4aca63 100644 --- a/middleware/static_serve.go +++ b/middleware/static_serve.go @@ -54,6 +54,12 @@ var ( errNotAllowQueryString = getStaticServeError("static serve not allow query string", http.StatusBadRequest) errNotFound = getStaticServeError("static file not found", http.StatusNotFound) errOutOfPath = getStaticServeError("out of path", http.StatusBadRequest) + + defaultCompressTypes = []string{ + "text", + "javascript", + "json", + } ) func (fs *FS) outOfPath(file string) bool { @@ -131,6 +137,19 @@ func doGzip(buf []byte, level int) ([]byte, error) { return b.Bytes(), nil } +func isCompressable(contentType string) bool { + compressable := false + for _, v := range defaultCompressTypes { + if compressable { + break + } + if strings.Contains(contentType, v) { + compressable = true + } + } + return compressable +} + // NewStaticServe create a static servce middleware func NewStaticServe(staticFile StaticFile, config StaticServeConfig) cod.Handler { if config.Path == "" { @@ -197,7 +216,9 @@ func NewStaticServe(staticFile StaticFile, config StaticServeConfig) cod.Handler c.SetHeader(cod.HeaderLastModified, lmd) } } - if config.Gzip && len(buf) >= config.CompressMinLength { + if config.Gzip && + len(buf) >= config.CompressMinLength && + isCompressable(contentType) { gzipBuf, e := doGzip(buf, 0) // 如果压缩成功,则使用压缩数据 // 失败则忽略 diff --git a/middleware/static_serve_test.go b/middleware/static_serve_test.go index 33cc276..811213a 100644 --- a/middleware/static_serve_test.go +++ b/middleware/static_serve_test.go @@ -146,6 +146,25 @@ func TestStaticServe(t *testing.T) { } }) + t.Run("not compresss", func(t *testing.T) { + fn := NewStaticServe(staticFile, StaticServeConfig{ + Path: staticPath, + Mount: "/static", + Gzip: true, + CompressMinLength: 1, + }) + req := httptest.NewRequest("GET", "/static/banner.jpg", nil) + res := httptest.NewRecorder() + c := cod.NewContext(res, req) + c.Next = func() error { + return nil + } + err := fn(c) + if err != nil || c.Headers.Get(cod.HeaderContentEncoding) == "gzip" { + t.Fatalf("serve image fail, %v", err) + } + }) + t.Run("get index.html", func(t *testing.T) { fn := NewStaticServe(staticFile, StaticServeConfig{ Path: staticPath,