/
decompress.go
93 lines (73 loc) · 2.51 KB
/
decompress.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
package middleware
import (
"compress/gzip"
"io"
"net/http"
"sync"
"github.com/datumforge/echox"
)
// DecompressConfig defines the config for Decompress middleware.
type DecompressConfig struct {
// Skipper defines a function to skip middleware.
Skipper Skipper
// GzipDecompressPool defines an interface to provide the sync.Pool used to create/store Gzip readers
GzipDecompressPool Decompressor
}
// GZIPEncoding content-encoding header if set to "gzip", decompress body contents.
const GZIPEncoding string = "gzip"
// Decompressor is used to get the sync.Pool used by the middleware to get Gzip readers
type Decompressor interface {
gzipDecompressPool() sync.Pool
}
// DefaultGzipDecompressPool is the default implementation of Decompressor interface
type DefaultGzipDecompressPool struct {
}
func (d *DefaultGzipDecompressPool) gzipDecompressPool() sync.Pool {
return sync.Pool{New: func() interface{} { return new(gzip.Reader) }}
}
// Decompress decompresses request body based if content encoding type is set to "gzip" with default config
func Decompress() echox.MiddlewareFunc {
return DecompressWithConfig(DecompressConfig{})
}
// DecompressWithConfig returns a decompress middleware with config or panics on invalid configuration.
func DecompressWithConfig(config DecompressConfig) echox.MiddlewareFunc {
return toMiddlewareOrPanic(config)
}
// ToMiddleware converts DecompressConfig to middleware or returns an error for invalid configuration
func (config DecompressConfig) ToMiddleware() (echox.MiddlewareFunc, error) {
if config.Skipper == nil {
config.Skipper = DefaultSkipper
}
if config.GzipDecompressPool == nil {
config.GzipDecompressPool = &DefaultGzipDecompressPool{}
}
return func(next echox.HandlerFunc) echox.HandlerFunc {
pool := config.GzipDecompressPool.gzipDecompressPool()
return func(c echox.Context) error {
if config.Skipper(c) {
return next(c)
}
if c.Request().Header.Get(echox.HeaderContentEncoding) != GZIPEncoding {
return next(c)
}
i := pool.Get()
gr, ok := i.(*gzip.Reader)
if !ok || gr == nil {
return echox.NewHTTPError(http.StatusInternalServerError, i.(error).Error())
}
defer pool.Put(gr)
b := c.Request().Body
defer b.Close()
if err := gr.Reset(b); err != nil {
if err == io.EOF { //ignore if body is empty
return next(c)
}
return err
}
// only Close gzip reader if it was set to a proper gzip source otherwise it will panic on close.
defer gr.Close()
c.Request().Body = gr
return next(c)
}
}, nil
}