TL;DR:它们是相同的类型,在两个用例中的使用略有不同,并且为服务这些用例而进行了不同的初始化
区别仅在于用法 - 它们是同一类型http.Request。 http.NewRequest 用于更多的“生产”用例,即客户端 - “创建一个新请求以发送到服务器”。在编写 HTTP 服务器时,创建测试请求偶尔会很有用,httptest.NewRequest 就是这样做的。 http.NewRequest 的文档在这里很有帮助:
NewRequest 返回一个适用于 Client.Do 或
运输.往返。创建用于测试服务器的请求
Handler,要么使用 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
注意“对于客户端请求”与“对于服务器请求”。
如果您看到一个不使用httptest.NewRequest 的地方,可能是因为:
- 他们不知道
- 或者他们需要更仔细的微调,
http.NewRequest 没有提供