2015-05-15 12:29:14 -07:00
|
|
|
package middleware
|
|
|
|
|
2016-02-04 14:40:08 -08:00
|
|
|
import (
|
|
|
|
"compress/gzip"
|
|
|
|
"io"
|
|
|
|
"io/ioutil"
|
|
|
|
"net/http"
|
|
|
|
"strings"
|
|
|
|
"sync"
|
|
|
|
|
|
|
|
"github.com/labstack/echo"
|
|
|
|
"github.com/labstack/echo/engine"
|
|
|
|
)
|
|
|
|
|
|
|
|
type (
|
2016-03-14 13:55:38 -07:00
|
|
|
GzipConfig struct {
|
|
|
|
Level int
|
2016-02-17 21:01:47 -08:00
|
|
|
}
|
|
|
|
|
2016-03-10 12:05:33 -08:00
|
|
|
gzipResponseWriter struct {
|
2016-02-04 14:40:08 -08:00
|
|
|
engine.Response
|
2016-03-10 12:05:33 -08:00
|
|
|
io.Writer
|
2016-02-04 14:40:08 -08:00
|
|
|
}
|
|
|
|
)
|
|
|
|
|
2016-03-14 13:55:38 -07:00
|
|
|
var (
|
|
|
|
defaultGzipConfig = GzipConfig{
|
|
|
|
Level: gzip.DefaultCompression,
|
|
|
|
}
|
|
|
|
)
|
|
|
|
|
2016-02-17 21:01:47 -08:00
|
|
|
// Gzip returns a middleware which compresses HTTP response using gzip compression
|
|
|
|
// scheme.
|
2016-03-14 13:55:38 -07:00
|
|
|
func Gzip() echo.MiddlewareFunc {
|
|
|
|
return GzipFromConfig(defaultGzipConfig)
|
|
|
|
}
|
|
|
|
|
|
|
|
// GzipFromConfig return `Gzip` middleware from config.
|
|
|
|
func GzipFromConfig(config GzipConfig) echo.MiddlewareFunc {
|
|
|
|
pool := gzipPool(config)
|
|
|
|
scheme := "gzip"
|
|
|
|
|
2016-02-18 22:50:40 -08:00
|
|
|
return func(next echo.Handler) echo.Handler {
|
2016-02-17 21:49:31 -08:00
|
|
|
return echo.HandlerFunc(func(c echo.Context) error {
|
|
|
|
c.Response().Header().Add(echo.Vary, echo.AcceptEncoding)
|
|
|
|
if strings.Contains(c.Request().Header().Get(echo.AcceptEncoding), scheme) {
|
2016-03-10 12:05:33 -08:00
|
|
|
w := pool.Get().(*gzip.Writer)
|
2016-03-10 16:35:20 -08:00
|
|
|
w.Reset(c.Response().Writer())
|
2016-02-17 21:49:31 -08:00
|
|
|
defer func() {
|
|
|
|
w.Close()
|
2016-03-10 12:05:33 -08:00
|
|
|
pool.Put(w)
|
2016-02-17 21:49:31 -08:00
|
|
|
}()
|
2016-03-10 16:35:20 -08:00
|
|
|
g := gzipResponseWriter{Response: c.Response(), Writer: w}
|
2016-02-17 21:49:31 -08:00
|
|
|
c.Response().Header().Set(echo.ContentEncoding, scheme)
|
2016-03-10 16:35:20 -08:00
|
|
|
c.Response().SetWriter(g)
|
2016-02-17 21:49:31 -08:00
|
|
|
}
|
2016-03-17 13:24:52 -07:00
|
|
|
return next.Handle(c)
|
2016-02-17 21:49:31 -08:00
|
|
|
})
|
|
|
|
}
|
2016-02-17 21:01:47 -08:00
|
|
|
}
|
|
|
|
|
2016-03-10 12:05:33 -08:00
|
|
|
func (g gzipResponseWriter) Write(b []byte) (int, error) {
|
|
|
|
if g.Header().Get(echo.ContentType) == "" {
|
|
|
|
g.Header().Set(echo.ContentType, http.DetectContentType(b))
|
2016-02-04 14:40:08 -08:00
|
|
|
}
|
2016-03-10 12:05:33 -08:00
|
|
|
return g.Writer.Write(b)
|
2016-02-04 14:40:08 -08:00
|
|
|
}
|
|
|
|
|
2016-03-14 13:55:38 -07:00
|
|
|
func gzipPool(config GzipConfig) sync.Pool {
|
|
|
|
return sync.Pool{
|
|
|
|
New: func() interface{} {
|
|
|
|
w, _ := gzip.NewWriterLevel(ioutil.Discard, config.Level)
|
|
|
|
return w
|
|
|
|
},
|
|
|
|
}
|
2016-02-04 14:40:08 -08:00
|
|
|
}
|