最近在開發一個功能時,須要經過 http 協議上報大量的日誌內容,可是在 Go 標準庫裏的 http client 的 API 是這樣的:git
http.NewRequest(method, url string, body io.Reader)
body 是經過io.Reader
接口來傳遞,並無暴露一個io.Writer
接口來提供寫入的辦法,先來看看正常狀況下怎麼寫入一個body
,示例:github
buf := bytes.NewBuffer([]byte("hello")) http.Post("localhost:8099/report","text/pain",buf)
須要先把要寫入的數據放在Buffer
中,放內存緩存着,可是我須要寫入大量
的數據,若是都放內存裏確定要 OOM 了,http client 並無提供流式寫入
的方法,我這麼大的數據量直接用Buffer
確定是不行的,最後在 google 了一番以後找到了解決辦法。golang
調用io.pipe()
方法會返回Reader
和Writer
接口實現對象,經過Writer
寫數據,Reader
就能夠讀到,利用這個特性就能夠實現流式的寫入,開一個協程來寫,而後把Reader
傳遞到方法中,就能夠實現 http client body 的流式寫入了。緩存
pr, rw := io.Pipe() // 開協程寫入大量數據 go func(){ for i := 0; i < 100000; i++ { rw.Write([]byte(fmt.Sprintf("line:%d\r\n", i))) } rw.Close() }() // 傳遞Reader http.Post("localhost:8099/report","text/pain",buf)
瞭解 go 中 http client 對於 body 的傳輸是如何處理的。性能
在構建 Request 的時候,會斷言 body 參數的類型,當類型爲*bytes.Buffer
、*bytes.Reader
、*strings.Reader
的時候,能夠直接經過Len()
方法取出長度,用於Content-Length
請求頭,相關代碼net/http/request.go#L872-L914:優化
if body != nil { switch v := body.(type) { case *bytes.Buffer: req.ContentLength = int64(v.Len()) buf := v.Bytes() req.GetBody = func() (io.ReadCloser, error) { r := bytes.NewReader(buf) return ioutil.NopCloser(r), nil } case *bytes.Reader: req.ContentLength = int64(v.Len()) snapshot := *v req.GetBody = func() (io.ReadCloser, error) { r := snapshot return ioutil.NopCloser(&r), nil } case *strings.Reader: req.ContentLength = int64(v.Len()) snapshot := *v req.GetBody = func() (io.ReadCloser, error) { r := snapshot return ioutil.NopCloser(&r), nil } default: } if req.GetBody != nil && req.ContentLength == 0 { req.Body = NoBody req.GetBody = func() (io.ReadCloser, error) { return NoBody, nil } } }
在連接創建的時候,會經過body
和上一步中獲得的ContentLength
來進行判斷,若是body!=nil
而且ContentLength==0
時,可能就會啓用Chunked
編碼進行傳輸,相關代碼net/http/transfer.go#L82-L96:google
case *Request: if rr.ContentLength != 0 && rr.Body == nil { return nil, fmt.Errorf("http: Request.ContentLength=%d with nil Body", rr.ContentLength) } t.Method = valueOrDefault(rr.Method, "GET") t.Close = rr.Close t.TransferEncoding = rr.TransferEncoding t.Header = rr.Header t.Trailer = rr.Trailer t.Body = rr.Body t.BodyCloser = rr.Body // 當body爲非nil,而且ContentLength==0時,這裏返回-1 t.ContentLength = rr.outgoingLength() // TransferEncoding沒有手動設置,而且請求方法爲PUT、POST、PATCH時,會啓用chunked編碼傳輸 if t.ContentLength < 0 && len(t.TransferEncoding) == 0 && t.shouldSendChunkedRequestBody() { t.TransferEncoding = []string{"chunked"} }
按照對源碼的理解,能夠得知在使用io.pipe()
方法進行流式傳輸時,會使用chunked
編碼進行傳輸,經過如下代碼進行驗證:編碼
func main(){ http.HandleFunc("/report", func(writer http.ResponseWriter, request *http.Request) { }) http.ListenAndServe(":8099", nil) }
func main(){ pr, rw := io.Pipe() go func(){ for i := 0; i < 100; i++ { rw.Write([]byte(fmt.Sprintf("line:%d\r\n", i))) } rw.Close() }() http.Post("localhost:8099/report","text/pain",buf) }
先運行服務端,而後運行客戶端,而且使用WireShake
進行抓包分析,結果以下:url
能夠看到和預想的結果同樣。spa
在數據量大的時候chunked
編碼會增長額外的開銷,包括編解碼和額外的報文開銷,能不能不用chunked
編碼來進行流式傳輸
呢?經過源碼能夠得知,當ContentLength
不爲 0 時,若是能預先計算出待傳輸的body size
,是否是就能避免chunked
編碼呢?思路就到這,接着就是寫代碼驗證:
func main(){ http.HandleFunc("/report", func(writer http.ResponseWriter, request *http.Request) { }) http.ListenAndServe(":8099", nil) }
count := 100 line := []byte("line\r\n") pr, rw := io.Pipe() go func() { for i := 0; i < count; i++ { rw.Write(line) } rw.Close() }() // 構造request對象 request, err := http.NewRequest("POST", "http://localhost:8099/report", pr) if err != nil { log.Fatal(err) } // 提早計算出ContentLength request.ContentLength = int64(len(line) * count) // 發起請求 http.DefaultClient.Do(request)
抓包結果:
能夠看到確實直接使用的Content-Length
進行傳輸,沒有進行chunked
編碼了。
本文的目的主要是記錄 go 語言中http client
如何進行流式的寫入,並經過閱讀源碼瞭解http client
內部對 body 的寫入是如何進行處理的,經過兩個驗證能夠得知,若是能提早計算出ContentLength
而且對性能要求比較苛刻的狀況下,能夠經過手動設置ContentLength
來優化性能。