net/http the difference between server request and client request

huangapple go评论87阅读模式
英文:

net/http the difference between server request and client request

问题

当我阅读Golang的net/http包的源代码时,经常会提到客户端请求和服务器请求之间的区别。我想知道这两者通常在什么情况下使用(当然,客户端请求是很容易理解的,并且在前后端分离架构的网站中广泛使用)。

例如:

//
// 对于客户端请求,nil的Body表示请求没有主体,比如GET请求。HTTP客户端的传输层负责调用Close方法。
//
// 对于服务器请求,请求主体始终是非nil的,但当没有主体时,它会立即返回EOF。服务器会关闭请求主体。ServeHTTP处理程序不需要关闭它。
//
// Body必须允许在Close的同时调用Read。特别是,调用Close应该解除等待输入的Read的阻塞。
Body io.ReadCloser```

<details>
<summary>英文:</summary>

When I read the source code of the Golang `net/http ` package, it always mentioned **the difference between client requests and server requests**. I want to know when these two are generally used, (of course, client requests are well understood and are widely used in websites with front-end and back-end separation architectures)

e.g.
```// Body is the request&#39;s body.
	//
	// For client requests, a nil body means the request has no
	// body, such as a GET request. The HTTP Client&#39;s Transport
	// is responsible for calling the Close method.
	//
	// For server requests, the Request Body is always non-nil
	// but will return EOF immediately when no body is present.
	// The Server will close the request body. The ServeHTTP
	// Handler does not need to.
	//
	// Body must allow Read to be called concurrently with Close.
	// In particular, calling Close should unblock a Read waiting
	// for input.
	Body io.ReadCloser

</details>


# 答案1
**得分**: 1

你可以使用`http.NewRequest`创建一个`Request`,然后设置它的字段,并调用`Client.Do`来发送请求。在这种情况下,如果请求有请求体,客户端必须设置`Request.Body`变量。

当服务器端处理这个请求时,会创建一个新的`http.Request`实例,这是一个服务器请求。对于这种用法,`Body`永远不会是nil。

<details>
<summary>英文:</summary>

You can create a `Request` using `http.NewRequest`, then set its fields, and call `Client.Do` to issue the request. In this case, the `Request.Body` is a variable the client has to set if the request has a body. 

When this request is handled on the server side, a new instance of `http.Request` is created, and that is a server request. For this use, the `Body` is never nil.

</details>



huangapple
  • 本文由 发表于 2022年8月2日 09:13:28
  • 转载请务必保留本文链接:https://go.coder-hub.com/73201035.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定