背景

最近在開發一個功能時,需要通過 http 協議上報大量的日誌內容,但是在 Go 標準庫裏的 http client 的 API 是這樣的:

http.NewRequest(method, url string, body io.Reader)

body 是通過 io.Reader 接口來傳遞,並沒有暴露一個 io.Writer 接口來提供寫入的辦法,先來看看正常情況下怎麼寫入一個 body ,示例:

buf := bytes.NewBuffer([]byte("hello"))
http.Post("localhost:8099/report","text/pain",buf)

需要先把要寫入的數據放在 Buffer 中,放內存緩存着,但是我需要寫入 大量 的數據,如果都放內存裏肯定要 OOM 了,http client 並沒有提供 流式寫入 的方法,我這麼大的數據量直接用 Buffer 肯定是不行的,最後在 google 了一番之後找到了解決辦法。

使用 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-L96

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 進行抓包分析,結果如下:

可以看到和預想的結果一樣。

驗證(二)

在數據量大的時候 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 來優化性能。

歡迎關注我們的微信公衆號,每天學習Go知識

相關文章