2015-05-15 21:29:14 +02:00
|
|
|
package middleware
|
|
|
|
|
|
|
|
import (
|
|
|
|
"compress/gzip"
|
|
|
|
"io"
|
|
|
|
"strings"
|
|
|
|
|
2015-05-22 13:40:01 +02:00
|
|
|
"net/http"
|
2015-05-23 05:26:52 +02:00
|
|
|
|
|
|
|
"github.com/labstack/echo"
|
2015-05-15 21:29:14 +02:00
|
|
|
)
|
|
|
|
|
|
|
|
type (
|
2015-05-16 00:24:47 +02:00
|
|
|
gzipWriter struct {
|
2015-05-15 21:29:14 +02:00
|
|
|
io.Writer
|
2015-05-22 13:40:01 +02:00
|
|
|
http.ResponseWriter
|
2015-05-15 21:29:14 +02:00
|
|
|
}
|
|
|
|
)
|
|
|
|
|
2015-05-22 13:40:01 +02:00
|
|
|
func (w gzipWriter) Write(b []byte) (int, error) {
|
|
|
|
return w.Writer.Write(b)
|
2015-05-15 21:29:14 +02:00
|
|
|
}
|
|
|
|
|
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-23 05:26:52 +02:00
|
|
|
if (c.Request().Header.Get(echo.Upgrade)) != echo.WebSocket && // Skip for WebSocket
|
|
|
|
strings.Contains(c.Request().Header.Get(echo.AcceptEncoding), scheme) {
|
2015-05-22 13:40:01 +02:00
|
|
|
w := gzip.NewWriter(c.Response().Writer())
|
2015-05-18 07:54:29 +02:00
|
|
|
defer w.Close()
|
2015-05-22 13:40:01 +02:00
|
|
|
gw := gzipWriter{Writer: w, ResponseWriter: c.Response().Writer()}
|
|
|
|
c.Response().Header().Set(echo.ContentEncoding, scheme)
|
|
|
|
c.Response().SetWriter(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
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|