用户登录
用户注册

分享至

Go语言HTTP请求流式写入body的示例代码

  • 作者: o决恋25304408
  • 来源: 51数据库
  • 2021-08-02

背景

最近在开发一个功能时,需要通过 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() 方法会返回 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  :

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语言http请求流式写入body的文章就介绍到这了,更多相关go语言http请求内容请搜索以前的文章或继续浏览下面的相关文章希望大家以后多多支持!

软件
前端设计
程序设计
Java相关