Golang中为什么http.Client在执行请求时会关闭body流?

Golang中为什么http.Client在执行请求时会关闭body流? 最近,在处理一个非常奇怪的行为时,我发现当将文件句柄作为请求体传递给HTTP POST请求并随后执行该请求后,文件被关闭了。

之后,我进行了一些测试,发现请求体确实在请求时被http包的RoundTripper关闭了。

下面,你可以看到该行为的一个简要演示。

package main

import (
	"fmt"
	"io"
	"net/http"
)

type dummy struct {
	IsClosed bool
}

func (d dummy) Read(p []byte) (n int, err error) {
	return 0, nil
}

func (d *dummy) Close() error {
	d.IsClosed = true
	return nil
}

func main() {
	d := dummy{}
	r, _ := http.NewRequest("POST", "http://localhost:80", &d)
	http.DefaultClient.Do(r)
	fmt.Println(d.IsClosed)
	// → true
}

我实际上非常好奇,为什么决定在执行请求时关闭作为请求体传递的流。在我看来,这非常违反直觉,程序本身应该负责处理流的关闭状态。

我也查看了执行关闭操作的代码,但没有找到任何文档说明为什么要这样做。如果能听到你对此的看法,那将非常有趣。如果你知道这样做的原因,请告诉我。


更多关于Golang中为什么http.Client在执行请求时会关闭body流?的实战教程也可以访问 https://www.itying.com/category-94-b0.html

回到顶部