V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
The Go Programming Language
http://golang.org/
Go Playground
Go Projects
Revel Web Framework
lcj2class
V2EX  ›  Go 编程语言

Examples For Using io.Pipe in Go

  •  
  •   lcj2class · 2020-03-01 10:24:35 +08:00 · 1456 次点击
    这是一个创建于 1516 天前的主题,其中的信息可能已经有所发展或是发生改变。

    真的很喜欢这个功能,小巧精悍。最近在一个项目中用到了,大概是这样的:

    项目中有一个自定义的 http.RoundTripper,之前都是纯文本发送数据,现在想加上 gzip 压缩。

    func (crt roundTripper) RoundTrip(r *http.Request) (*http.Response, error) {
    	if crt.compress {
    		r.Header.Add(headerContentEncoding, "gzip")
    		raw := r.Body
    		pr, pw := io.Pipe()
    		go func() {
    			defer pw.Close()
    			gw := gzip.NewWriter(pw)
    			defer gw.Close()
    			if n, err := io.Copy(gw, raw); err != nil {
    				crt.log.Logf("gzip body failed. written: %d, err: %v ", n, err)
    			}
    		}()
    		// set 0 enable Transfer-Encoding:chunked
    		r.ContentLength = 0
    		r.Body = pr
    	}
    	return crt.r.RoundTrip(r)
    }
    
    1 条回复    2020-03-05 13:23:50 +08:00
    kuro1
        1
    kuro1  
       2020-03-05 13:23:50 +08:00
    这里的 io.copy 倒是让我学到了
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   3555 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 26ms · UTC 10:54 · PVG 18:54 · LAX 03:54 · JFK 06:54
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.