2015-05-15 21:29:14 +02:00
|
|
|
package middleware
|
|
|
|
|
|
|
|
import (
|
|
|
|
"compress/gzip"
|
|
|
|
"io"
|
|
|
|
"strings"
|
|
|
|
|
|
|
|
"github.com/labstack/echo"
|
|
|
|
)
|
|
|
|
|
|
|
|
type (
|
2015-05-16 00:24:47 +02:00
|
|
|
gzipWriter struct {
|
2015-05-15 21:29:14 +02:00
|
|
|
io.Writer
|
|
|
|
*echo.Response
|
|
|
|
}
|
|
|
|
)
|
|
|
|
|
2015-05-16 00:24:47 +02:00
|
|
|
func (g gzipWriter) Write(b []byte) (int, error) {
|
2015-05-15 21:29:14 +02:00
|
|
|
return g.Writer.Write(b)
|
|
|
|
}
|
|
|
|
|
2015-05-18 07:54:29 +02:00
|
|
|
// Gzip returns a middleware which compresses HTTP response using gzip compression
|
|
|
|
// scheme.
|
2015-05-15 21:29:14 +02:00
|
|
|
func Gzip() echo.MiddlewareFunc {
|
|
|
|
scheme := "gzip"
|
|
|
|
|
|
|
|
return func(h echo.HandlerFunc) echo.HandlerFunc {
|
2015-05-20 23:38:51 +02:00
|
|
|
return func(c *echo.Context) error {
|
2015-05-18 07:54:29 +02:00
|
|
|
if strings.Contains(c.Request.Header.Get(echo.AcceptEncoding), scheme) {
|
2015-05-20 23:38:51 +02:00
|
|
|
w := gzip.NewWriter(c.Response.Writer())
|
2015-05-18 07:54:29 +02:00
|
|
|
defer w.Close()
|
|
|
|
gw := gzipWriter{Writer: w, Response: c.Response}
|
|
|
|
c.Response.Header().Set(echo.ContentEncoding, scheme)
|
2015-05-20 23:38:51 +02:00
|
|
|
c.Response = echo.NewResponse(gw)
|
2015-05-15 21:29:14 +02:00
|
|
|
}
|
2015-05-18 07:54:29 +02:00
|
|
|
return h(c)
|
2015-05-15 21:29:14 +02:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|