Go語言HTTP請求流式寫入body

背景

最近在開發一個功能時,須要經過 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

調用io.pipe()方法會返回ReaderWriter接口實現對象,經過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-L96google

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來優化性能。

相關文章
相關標籤/搜索