1 Star 0 Fork 0

zhangjungang/beats

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
克隆/下载
enc.go 1.21 KB
一键复制 编辑 原始数据 按行查看 历史
package http
import (
"compress/gzip"
"errors"
"io"
"net/http"
"strings"
)
type contentEncoder interface {
AddHeaders(*http.Header)
Encode(to io.Writer, from io.Reader) error
}
type nilEncoder struct{}
type gzipEncoder struct {
gz *gzip.Writer
}
var plainEncoder = nilEncoder{}
func getContentEncoder(name string, level int) (contentEncoder, error) {
name = strings.ToLower(name)
if name == "gzip" {
return newGZIPEncoder(level)
}
if name != "" {
return nil, errors.New("invalid content encoder")
}
return plainEncoder, nil
}
func (nilEncoder) AddHeaders(_ *http.Header) {}
func (nilEncoder) Encode(to io.Writer, from io.Reader) error {
_, err := io.Copy(to, from)
return err
}
func newGZIPEncoder(level int) (*gzipEncoder, error) {
w, err := gzip.NewWriterLevel(nil, level)
if err != nil {
return nil, err
}
return &gzipEncoder{w}, nil
}
func (e *gzipEncoder) AddHeaders(h *http.Header) {
h.Add("Content-Type", "application/json; charset=UTF-8")
h.Add("Content-Encoding", "gzip")
}
func (e *gzipEncoder) Encode(to io.Writer, from io.Reader) error {
e.gz.Reset(to)
if _, err := io.Copy(e.gz, from); err != nil {
return err
}
if err := e.gz.Flush(); err != nil {
return err
}
return nil
}
Loading...
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
1
https://gitee.com/zhangjungang/beats.git
git@gitee.com:zhangjungang/beats.git
zhangjungang
beats
beats
v6.1.0

搜索帮助

0d507c66 1850385 C8b1a773 1850385