2015-05-15 21:29:14 +02:00
|
|
|
package middleware
|
|
|
|
|
|
|
|
import (
|
|
|
|
"compress/gzip"
|
|
|
|
"strings"
|
|
|
|
|
2015-05-22 13:40:01 +02:00
|
|
|
"net/http"
|
2015-05-23 05:26:52 +02:00
|
|
|
|
2015-06-10 00:24:01 +02:00
|
|
|
"bufio"
|
|
|
|
"net"
|
|
|
|
|
2015-05-23 05:26:52 +02:00
|
|
|
"github.com/labstack/echo"
|
2015-06-10 00:24:01 +02:00
|
|
|
"io"
|
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-06-10 00:24:01 +02:00
|
|
|
func (w gzipWriter) Flush() {
|
|
|
|
w.Writer.(*gzip.Writer).Flush()
|
|
|
|
}
|
|
|
|
|
|
|
|
func (w gzipWriter) Hijack() (net.Conn, *bufio.ReadWriter, error) {
|
|
|
|
return w.ResponseWriter.(http.Hijacker).Hijack()
|
|
|
|
}
|
|
|
|
|
|
|
|
func (w *gzipWriter) CloseNotify() <-chan bool {
|
|
|
|
return w.ResponseWriter.(http.CloseNotifier).CloseNotify()
|
|
|
|
}
|
|
|
|
|
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-06-10 00:24:01 +02:00
|
|
|
if 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-06-10 00:24:01 +02:00
|
|
|
if err := h(c); err != nil {
|
|
|
|
c.Error(err)
|
|
|
|
}
|
|
|
|
return nil
|
2015-05-15 21:29:14 +02:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|