登录
首页 >  Golang >  Go问答

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

来源:stackoverflow

时间:2024-04-12 16:21:33 244浏览 收藏

在IT行业这个发展更新速度很快的行业,只有不停止的学习,才不会被行业所淘汰。如果你是Golang学习者,那么本文《Golang的“net/http”中客户端HTTP请求和服务器HTTP请求有什么区别》就很适合你!本篇内容主要包括##content_title##,希望对大家的知识积累有所帮助,助力实战开发!

问题内容

我见过人们使用“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.requesthttp.newrequest 用于更多“生产”用例,即客户端 - “创建一个新请求发送到服务器”。在编写 http 服务器时,创建测试请求有时很有用,这就是 httptest.newrequest 所做的事情。 http.newrequest 的文档在这里很有帮助:

newrequest 返回适合与 client.do 一起使用的请求或 运输.往返。创建用于测试服务器的请求 处理程序,要么使用 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 不提供

以上就是本文的全部内容了,是否有顺利帮助你解决问题?若是能给你带来学习上的帮助,请大家多多支持golang学习网!更多关于Golang的相关知识,也可关注golang学习网公众号。

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>