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

时间:2019-04-28 12:12:15

标签: http go

我已经看到人们使用“ net / http”包的NewRequest()方法来测试API。为什么不使用“ net / http / httptesting”中的NewRequest()方法?有什么不同?文档建议the following

// To generate a client HTTP request instead of a server request, see
// the NewRequest function in the net/http package.

例如,处理Cookie有什么区别?两者似乎非常相似。

1 个答案:

答案 0 :(得分:1)

TL; DR:它们是同一类型,在两个用例中使用的方式略有不同,并且为服务于这些用例而进行了不同的初始化


不同之处仅在于用法-它们是同一类型http.Requesthttp.NewRequest用于客户端的更多“生产”用例-“创建要发送到服务器的新请求”。编写HTTP服务器时,偶尔创建测试请求非常有用,httptest.NewRequest就是这样做的。 http.NewRequest的文档在这里很有帮助:

  

NewRequest返回适合与Client.Do一起使用的请求   Transport.RoundTrip。创建用于测试服务器的请求   处理程序,可以使用net / http / httptest中的NewRequest函数   包,使用ReadRequest或手动更新Request字段。看到   请求类型的文档以了解入站之间的区别   和出站请求字段。

如果您查看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的地方,可能是因为:

  1. 他们不知道
  2. 或者他们需要更仔细的微调,{@ {1}}不会提供