Ai
1 Star 0 Fork 1

flanche/echo

forked from guapian/echo 
加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
克隆/下载
compress.go 1.55 KB
一键复制 编辑 原始数据 按行查看 历史
Vishal Rana 提交于 2016-02-09 14:17 +08:00 . Wrappers for handler and middleware
package middleware
import (
"bufio"
"compress/gzip"
"io"
"io/ioutil"
"net"
"net/http"
"strings"
"sync"
"github.com/labstack/echo"
"github.com/labstack/echo/engine"
)
type (
gzipWriter struct {
io.Writer
engine.Response
}
)
func (w gzipWriter) Write(b []byte) (int, error) {
if w.Header().Get(echo.ContentType) == "" {
w.Header().Set(echo.ContentType, http.DetectContentType(b))
}
return w.Writer.Write(b)
}
func (w gzipWriter) Flush() error {
return w.Writer.(*gzip.Writer).Flush()
}
func (w gzipWriter) Hijack() (net.Conn, *bufio.ReadWriter, error) {
return w.Response.(http.Hijacker).Hijack()
}
func (w *gzipWriter) CloseNotify() <-chan bool {
return w.Response.(http.CloseNotifier).CloseNotify()
}
var writerPool = sync.Pool{
New: func() interface{} {
return gzip.NewWriter(ioutil.Discard)
},
}
// Gzip returns a middleware which compresses HTTP response using gzip compression
// scheme.
func Gzip() echo.MiddlewareFunc {
return func(h echo.HandlerFunc) echo.HandlerFunc {
scheme := "gzip"
return 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
}
}
}
Loading...
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
1
https://gitee.com/flanche/echo.git
git@gitee.com:flanche/echo.git
flanche
echo
echo
v2.0.0-apha.1

搜索帮助