【问题标题】:What is the difference between client HTTP request and server HTTP request in Golang's "net/http"Golang的“net/http”中客户端HTTP请求和服务器HTTP请求有什么区别
【发布时间】:2019-04-28 12:12:15
【问题描述】:

我看到人们使用“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 会有什么不同?两者看起来非常相似。

【问题讨论】:

  • Request 字段和方法文档指出了客户端使用和服务器使用之间的区别。 httptest.NewRequest 初始化一个请求,就好像它已在服务器上收到一样。 http.NewRequest 初始化一个请求供客户端使用。

标签: http go


【解决方案1】:

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


区别仅在于用法 - 它们是同一类型http.Requesthttp.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 的地方,可能是因为:

  1. 他们不知道
  2. 或者他们需要更仔细的微调,http.NewRequest 没有提供

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-10-19
    • 2019-07-07
    • 2013-03-07
    • 2017-05-14
    • 2010-09-11
    相关资源
    最近更新 更多