Skip to content

Commit

Permalink
Merge pull request #36 from standcats/master
Browse files Browse the repository at this point in the history
feat : excluede paths by regex
  • Loading branch information
thinkerou authored Jun 9, 2020
2 parents af5a1ba + 44264cb commit 6ac096f
Show file tree
Hide file tree
Showing 3 changed files with 65 additions and 4 deletions.
27 changes: 27 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -99,3 +99,30 @@ func main() {
r.Run(":8080")
}
```


Customized Excluded Paths

```go
package main

import (
"fmt"
"net/http"
"time"

"github.com/gin-contrib/gzip"
"github.com/gin-gonic/gin"
)

func main() {
r := gin.Default()
r.Use(gzip.Gzip(gzip.DefaultCompression, gzip.WithExcludedPathsRegexs([]string{".*"})))
r.GET("/ping", func(c *gin.Context) {
c.String(http.StatusOK, "pong "+fmt.Sprint(time.Now().Unix()))
})

// Listen and Server in 0.0.0.0:8080
r.Run(":8080")
}
```
9 changes: 8 additions & 1 deletion handler.go
Original file line number Diff line number Diff line change
Expand Up @@ -73,5 +73,12 @@ func (g *gzipHandler) shouldCompress(req *http.Request) bool {
return false
}

return !g.ExcludedPaths.Contains(req.URL.Path)
if g.ExcludedPaths.Contains(req.URL.Path) {
return false
}
if g.ExcludedPathesRegexs.Contains(req.URL.Path) {
return false
}

return true
}
33 changes: 30 additions & 3 deletions options.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ package gzip
import (
"compress/gzip"
"net/http"
"regexp"
"strings"

"github.com/gin-gonic/gin"
Expand All @@ -18,9 +19,10 @@ var (
)

type Options struct {
ExcludedExtensions ExcludedExtensions
ExcludedPaths ExcludedPaths
DecompressFn func(c *gin.Context)
ExcludedExtensions ExcludedExtensions
ExcludedPaths ExcludedPaths
ExcludedPathesRegexs ExcludedPathesRegexs
DecompressFn func(c *gin.Context)
}

type Option func(*Options)
Expand All @@ -37,6 +39,12 @@ func WithExcludedPaths(args []string) Option {
}
}

func WithExcludedPathsRegexs(args []string) Option {
return func(o *Options) {
o.ExcludedPathesRegexs = NewExcludedPathesRegexs(args)
}
}

func WithDecompressFn(decompressFn func(c *gin.Context)) Option {
return func(o *Options) {
o.DecompressFn = decompressFn
Expand Down Expand Up @@ -74,6 +82,25 @@ func (e ExcludedPaths) Contains(requestURI string) bool {
return false
}

type ExcludedPathesRegexs []*regexp.Regexp

func NewExcludedPathesRegexs(regexs []string) ExcludedPathesRegexs {
result := make([]*regexp.Regexp, len(regexs), len(regexs))
for i, reg := range regexs {
result[i] = regexp.MustCompile(reg)
}
return result
}

func (e ExcludedPathesRegexs) Contains(requestURI string) bool {
for _, reg := range e {
if reg.MatchString(requestURI) {
return true
}
}
return false
}

func DefaultDecompressHandle(c *gin.Context) {
if c.Request.Body == nil {
return
Expand Down

0 comments on commit 6ac096f

Please sign in to comment.