Skip to content

Commit

Permalink
refactor: gzip only support for text/javascript/json
Browse files Browse the repository at this point in the history
  • Loading branch information
vicanso committed Dec 24, 2018
1 parent 011dda0 commit aa59f0c
Show file tree
Hide file tree
Showing 2 changed files with 41 additions and 1 deletion.
23 changes: 22 additions & 1 deletion middleware/static_serve.go
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down Expand Up @@ -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 == "" {
Expand Down Expand Up @@ -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)
// 如果压缩成功,则使用压缩数据
// 失败则忽略
Expand Down
19 changes: 19 additions & 0 deletions middleware/static_serve_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down

0 comments on commit aa59f0c

Please sign in to comment.