The Go Programming Language
http://golang.org/
Go Playground
Go Projects
Revel Web Framework
lcj2class

Examples For Using io.Pipe in Go

  •  
  •   lcj2class · Mar 1, 2020 · 1900 views
    This topic created in 2264 days ago, the information mentioned may be changed or developed.

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

    项目中有一个自定义的 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 replies    2020-03-05 13:23:50 +08:00
    kuro1
        1
    kuro1  
       Mar 5, 2020
    这里的 io.copy 倒是让我学到了
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   3197 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 32ms · UTC 14:30 · PVG 22:30 · LAX 07:30 · JFK 10:30
    ♥ Do have faith in what you're doing.