Go語言HTTP請求流式寫入body的示例代碼
背景
最近在開發(fā)一個功能時,需要通過 http 協(xié)議上報大量的日志內(nèi)容,但是在 Go 標(biāo)準(zhǔn)庫里的 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)
入的數(shù)據(jù)放在 Buffer 中,放內(nèi)存緩存著,但是我需要寫入 大量 的數(shù)據(jù),如果都放內(nèi)存里肯定要 OOM 了,http client 并沒有提供 流式寫入 的方法,我這么大的數(shù)據(jù)量直接用 Buffer 肯定是不行的,最后在 google 了一番之后找到了解決辦法。
使用 io.pipe
調(diào)用 io.pipe() 方法會返回 Reader 和 Writer 接口實現(xiàn)對象,通過 Writer 寫數(shù)據(jù), Reader 就可以讀到,利用這個特性就可以實現(xiàn)流式的寫入,開一個協(xié)程來寫,然后把 Reader 傳遞到方法中,就可以實現(xiàn) http client body 的流式寫入了。
代碼示例:
pr, rw := io.Pipe()
// 開協(xié)程寫入大量數(shù)據(jù)
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 的傳輸是如何處理的。
開始
在構(gòu)建 Request 的時候,會斷言 body 參數(shù)的類型,當(dāng)類型為 *bytes.Buffer 、 *bytes.Reader 、 *strings.Reader 的時候,可以直接通過 Len() 方法取出長度,用于 Content-Length 請求頭,相關(guān)代碼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 編碼進行傳輸,相關(guān)代碼 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
// 當(dāng)body為非nil,并且ContentLength==0時,這里返回-1
t.ContentLength = rr.outgoingLength()
// TransferEncoding沒有手動設(shè)置,并且請求方法為PUT、POST、PATCH時,會啟用chunked編碼傳輸
if t.ContentLength < 0 && len(t.TransferEncoding) == 0 && t.shouldSendChunkedRequestBody() {
t.TransferEncoding = []string{"chunked"}
}
驗證(一)
按照對源碼的理解,可以得知在使用 io.pipe() 方法進行流式傳輸時,會使用 chunked 編碼進行傳輸,通過以下代碼進行驗證:
服務(wù)端
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)
}
先運行服務(wù)端,然后運行客戶端,并且使用 WireShake 進行抓包分析,結(jié)果如下:

可以看到和預(yù)想的結(jié)果一樣。
驗證(二)
在數(shù)據(jù)量大的時候 chunked 編碼會增加額外的開銷,包括編解碼和額外的報文開銷,能不能不用 chunked 編碼來進行 流式傳輸 呢?通過源碼可以得知,當(dāng) ContentLength 不為 0 時,如果能預(yù)先計算出待傳輸?shù)?body size ,是不是就能避免 chunked 編碼呢?思路就到這,接著就是寫代碼驗證:
服務(wù)端
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()
}()
// 構(gòu)造request對象
request, err := http.NewRequest("POST", "http://localhost:8099/report", pr)
if err != nil {
log.Fatal(err)
}
// 提前計算出ContentLength
request.ContentLength = int64(len(line) * count)
// 發(fā)起請求
http.DefaultClient.Do(request)
抓包結(jié)果:

可以看到確實直接使用的 Content-Length 進行傳輸,沒有進行 chunked 編碼了。
總結(jié)
本文的目的主要是記錄 go 語言中 http client 如何進行流式的寫入,并通過閱讀源碼了解 http client 內(nèi)部對 body 的寫入是如何進行處理的,通過兩個驗證可以得知,如果能提前計算出 ContentLength 并且對性能要求比較苛刻的情況下,可以通過手動設(shè)置 ContentLength 來優(yōu)化性能。
到此這篇關(guān)于Go語言HTTP請求流式寫入body的文章就介紹到這了,更多相關(guān)Go語言HTTP請求內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
golang?gorm框架數(shù)據(jù)庫的連接操作示例
這篇文章主要為大家介紹了golang?gorm框架數(shù)據(jù)庫操作示例,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步早日升職加薪2022-04-04
一文帶大家了解Go語言中的內(nèi)聯(lián)優(yōu)化
內(nèi)聯(lián)優(yōu)化是一種常見的編譯器優(yōu)化策略,通俗來講,就是把函數(shù)在它被調(diào)用的地方展開,這樣可以減少函數(shù)調(diào)用所帶來的開銷,本文主要為大家介紹了Go中內(nèi)聯(lián)優(yōu)化的具體使用,需要的可以參考下2023-05-05
重學(xué)Go語言之?dāng)?shù)組的具體使用詳解
Go的數(shù)組是一種復(fù)合數(shù)據(jù)類型,在平時開發(fā)中并不常用,更常用的是切片(slice),可以把切片看作是能動態(tài)擴容的數(shù)組,切片的底層數(shù)據(jù)結(jié)構(gòu)就是數(shù)組,所以數(shù)組雖不常用,但仍然有必要掌握2023-02-02

