1
0
mirror of https://github.com/labstack/echo.git synced 2025-12-01 22:51:17 +02:00

Middleware and handler as closure

Signed-off-by: Vishal Rana <vr@labstack.com>
This commit is contained in:
Vishal Rana
2016-02-17 21:49:31 -08:00
parent c9a62e20b4
commit 88f307bedd
9 changed files with 180 additions and 230 deletions

View File

@@ -15,9 +15,8 @@ import (
)
type (
Gzip struct {
level int
priority int
GzipOption struct {
level int
}
gzipWriter struct {
@@ -26,44 +25,30 @@ type (
}
)
func NewGzip() *Gzip {
return &Gzip{}
}
func (g *Gzip) SetLevel(l int) {
g.level = l
}
func (g *Gzip) SetPriority(p int) {
g.priority = p
}
func (g *Gzip) Priority() int {
return g.priority
}
// Gzip returns a middleware which compresses HTTP response using gzip compression
// scheme.
func (*Gzip) Handle(h echo.Handler) echo.Handler {
scheme := "gzip"
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) {
w := writerPool.Get().(*gzip.Writer)
w.Reset(c.Response().Writer())
defer func() {
w.Close()
writerPool.Put(w)
}()
gw := gzipWriter{Writer: w, Response: c.Response()}
c.Response().Header().Set(echo.ContentEncoding, scheme)
c.Response().SetWriter(gw)
}
if err := h.Handle(c); err != nil {
c.Error(err)
}
return nil
})
func Gzip(option ...*GzipOption) echo.MiddlewareFunc {
return func(h echo.Handler) echo.Handler {
scheme := "gzip"
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) {
w := writerPool.Get().(*gzip.Writer)
w.Reset(c.Response().Writer())
defer func() {
w.Close()
writerPool.Put(w)
}()
gw := gzipWriter{Writer: w, Response: c.Response()}
c.Response().Header().Set(echo.ContentEncoding, scheme)
c.Response().SetWriter(gw)
}
if err := h.Handle(c); err != nil {
c.Error(err)
}
return nil
})
}
}
func (w gzipWriter) Write(b []byte) (int, error) {