[英]What is the difference between client HTTP request and server HTTP request in Golang's “net/http”
我见过人们使用“ net / http”包的NewRequest()
方法来测试API。 为什么不使用“ net / http / httptesting”中的NewRequest()
方法? 有什么不同? 文档建议以下内容 :
// To generate a client HTTP request instead of a server request, see
// the NewRequest function in the net/http package.
例如,处理Cookie有什么区别? 两者似乎非常相似。
TL; DR:它们是同一类型,在两个用例中使用的方式略有不同,并且在初始化时为使用这些用例的方式有所不同
区别仅在于用法-它们是相同的http.Request
类型。 http.NewRequest
用于客户端的更多“生产”用例-“创建要发送到服务器的新请求”。 编写HTTP服务器时,偶尔创建测试请求很有用,这就是httptest.NewRequest
所做的。 http.NewRequest
的文档在这里很有帮助:
NewRequest返回适合与Client.Do或Transport.RoundTrip一起使用的请求。 若要创建用于测试服务器处理程序的请求,请使用net / http / httptest程序包中的NewRequest函数,使用ReadRequest,或手动更新Request字段。 有关入站和出站请求字段之间的区别,请参见请求类型的文档。
如果查看http.Request类型的文档,则会发现类似以下内容:
// 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
没有提供
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.