1 Star 0 Fork 0

liuxuezhan / go-plugins

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
克隆/下载
gzip.go 1.37 KB
一键复制 编辑 原始数据 按行查看 历史
liuxuezhan 提交于 2021-08-18 17:52 . 'new'
// Package gzip is a micro plugin for gzipping http response
package gzip
import (
"compress/gzip"
"io"
"net/http"
"strings"
"gitee.com/liuxuezhan/cli-v0.2.0"
"gitee.com/liuxuezhan/go-micro-v1.18.0/plugin"
)
type gzipWriter struct {
http.Hijacker
io.Writer
http.ResponseWriter
}
type gzipper struct{}
func (g *gzipper) Flags() []cli.Flag {
return nil
}
func (g *gzipper) Commands() []cli.Command {
return nil
}
func (g *gzipper) Handler() plugin.Handler {
return func(h http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
// has gzip accept-encoding?
if !strings.Contains(r.Header.Get("Accept-Encoding"), "gzip") {
h.ServeHTTP(w, r)
return
}
// set the content-encoding
w.Header().Set("Content-Encoding", "gzip")
// create gzip writer
gz := gzip.NewWriter(w)
defer gz.Close()
// create http response writer
hj, _ := w.(http.Hijacker)
gzw := gzipWriter{hj, gz, w}
// serve the request
h.ServeHTTP(gzw, r)
})
}
}
func (g *gzipper) Init(ctx *cli.Context) error {
return nil
}
func (g *gzipper) String() string {
return "gzip"
}
func (w gzipWriter) WriteHeader(code int) {
w.Header().Del("Content-Length")
w.ResponseWriter.WriteHeader(code)
}
func (w gzipWriter) Write(b []byte) (int, error) {
return w.Writer.Write(b)
}
func NewPlugin() plugin.Plugin {
return new(gzipper)
}
1
https://gitee.com/liuxuezhan/go-plugins.git
git@gitee.com:liuxuezhan/go-plugins.git
liuxuezhan
go-plugins
go-plugins
db1d4b8b101e

搜索帮助

53164aa7 5694891 3bd8fe86 5694891