Golang的“net/http”中客户端HTTP请求和服务器HTTP请求有什么区别

Fed*_*ico 4 http go

我见过人们使用NewRequest()“net/http”包的方法来测试 API。为什么不使用NewRequest()“net/http/httptesting”中的方法?有什么不同?文档建议如下

// To generate a client HTTP request instead of a server request, see
// the NewRequest function in the net/http package.
Run Code Online (Sandbox Code Playgroud)

例如,处理 cookie 有何不同?两者似乎非常相似。

Eli*_*sky 5

TL;DR:它们是相同的类型,对于两个用例的使用略有不同,并且以不同的方式初始化以服务于这些用例


区别仅在于用途 - 它们是相同类型http.Requesthttp.NewRequest用于更“生产”的用例,即客户端 - “创建一个新请求发送到服务器”。在编写 HTTP 服务器时,创建测试请求有时很有用,这就是这样httptest.NewRequest做的。的文档http.NewRequest在这里很有帮助:

NewRequest 返回适合与 Client.Do 或 Transport.RoundTrip 一起使用的请求。要创建用于测试服务器处理程序的请求,请使用 net/http/httptest 包中的 NewRequest 函数、使用 ReadRequest 或手动更新请求字段。有关入站和出站请求字段之间的差异,请参阅请求类型的文档。

如果您检查http.Request type的文档,您会发现类似以下内容:

// URL specifies either the URI being requested (for server
// requests) or the URL to access (for client requests).
//
// For server requests, the URL is parsed from the URI
// supplied on the Request-Line as stored in RequestURI.  For
// most requests, fields other than Path and RawQuery will be
// empty. (See RFC 7230, Section 5.3)
//
// For client requests, the URL's Host specifies the server to
// connect to, while the Request's Host field optionally
// specifies the Host header value to send in the HTTP
// request.
URL *url.URL
Run Code Online (Sandbox Code Playgroud)

请注意“对于客户端请求”与“对于服务器请求”。

如果您看到某个地方没有使用httptest.NewRequest它,可能是因为:

  1. 他们不知道这一点
  2. 或者他们需要更仔细的微调,但http.NewRequest无法提供