主頁 > 知識庫 > Go語言HTTP請求流式寫入body的示例代碼

Go語言HTTP請求流式寫入body的示例代碼

熱門標簽:智能電銷機器人營銷 烏魯木齊人工電銷機器人系統(tǒng) 賺地圖標注的錢犯法嗎 長沙ai機器人電銷 廣東語音外呼系統(tǒng)供應商 地圖標注測試 澳門防封電銷卡 福州鐵通自動外呼系統(tǒng) 濮陽自動外呼系統(tǒng)代理

背景

最近在開發(fā)一個功能時,需要通過 http 協(xié)議上報大量的日志內容,但是在 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)

入的數(shù)據(jù)放在 Buffer 中,放內存緩存著,但是我需要寫入 大量 的數(shù)據(jù),如果都放內存里肯定要 OOM 了,http client 并沒有提供 流式寫入 的方法,我這么大的數(shù)據(jù)量直接用 Buffer 肯定是不行的,最后在 google 了一番之后找到了解決辦法。

使用 io.pipe

調用 io.pipe() 方法會返回 ReaderWriter 接口實現(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 的傳輸是如何處理的。

開始

在構建 Request 的時候,會斷言 body 參數(shù)的類型,當類型為 *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 進行抓包分析,結果如下:

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

驗證(二)

在數(shù)據(jù)量大的時候 chunked 編碼會增加額外的開銷,包括編解碼和額外的報文開銷,能不能不用 chunked 編碼來進行 流式傳輸 呢?通過源碼可以得知,當 ContentLength 不為 0 時,如果能預先計算出待傳輸?shù)?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)
// 發(fā)起請求
http.DefaultClient.Do(request)

抓包結果:

可以看到確實直接使用的 Content-Length 進行傳輸,沒有進行 chunked 編碼了。

總結

本文的目的主要是記錄 go 語言中 http client 如何進行流式的寫入,并通過閱讀源碼了解 http client 內部對 body 的寫入是如何進行處理的,通過兩個驗證可以得知,如果能提前計算出 ContentLength 并且對性能要求比較苛刻的情況下,可以通過手動設置 ContentLength 來優(yōu)化性能。

到此這篇關于Go語言HTTP請求流式寫入body的文章就介紹到這了,更多相關Go語言HTTP請求內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!

您可能感興趣的文章:
  • Go語言中利用http發(fā)起Get和Post請求的方法示例
  • go語言在請求http時加入自定義http header的方法
  • go語言簡單的處理http請求的函數(shù)實例
  • java通過HttpServletRequest獲取post請求中的body內容的方法
  • java獲取http請求的Header和Body的簡單方法

標簽:德州 太原 西雙版納 慶陽 調研邀請 阿克蘇 貴陽 廣西

巨人網(wǎng)絡通訊聲明:本文標題《Go語言HTTP請求流式寫入body的示例代碼》,本文關鍵詞  語言,HTTP,請求,流式,寫入,;如發(fā)現(xiàn)本文內容存在版權問題,煩請?zhí)峁┫嚓P信息告之我們,我們將及時溝通與處理。本站內容系統(tǒng)采集于網(wǎng)絡,涉及言論、版權與本站無關。
  • 相關文章
  • 下面列出與本文章《Go語言HTTP請求流式寫入body的示例代碼》相關的同類信息!
  • 本頁收集關于Go語言HTTP請求流式寫入body的示例代碼的相關信息資訊供網(wǎng)民參考!
  • 推薦文章