Home >Backend Development >Golang >How to reuse http.request.body in golang
The following column golang tutorial will introduce you to an example of the method of reusing http.request.body in golang. I hope it will be helpful to friends in need!
Problems and Scenarios
There is a need to distribute http.request.body in the business Scenes. For example, WeChat callback messages can only specify one address, so it is expected that a copy of the message can be sent to other services. Service B and Service A, which receives WeChat callbacks, process the WeChat callback information together.
This article will introduce in detail the relevant content of golang's reuse of http.request.body, and share it for everyone's reference and study. I won't say much below, let's take a look at the detailed introduction
Solution
The first consideration is to forward http.request directly. Use ReverseProxy to directly forward http.request from service A to service B. However, WeChat involves issues such as verification, and it is very troublesome to fully adjust it. So I changed my mind and planned to post the content of http.request.body directly to service B.
But http.request is readcloser. When we readAll http.request, we cannot read the information in http.request again.
How can I copy and use http.request.body?
where c represents the context of http
// 把request的内容读取出来 var bodyBytes []byte if c.Request.Body != nil { bodyBytes, _ = ioutil.ReadAll(c.Request.Body) } // 把刚刚读出来的再写进去 c.Request.Body = ioutil.NopCloser(bytes.NewBuffer(bodyBytes))
1. We first read the body from http.request and save it to a variable .
2. Then use the ioutil.NopCloser method to write the data in the variable back to http.request.
https://golang.org/pkg/io/ioutil/#NopCloser NopCloser returns a ReadCloser with a no-op Close method wrapping the provided Reader r.
NopCloser wraps Reader r with a no-operation Close method and returns a ReadCloser interface.
So we can use c.request again for processing.
The above is the detailed content of How to reuse http.request.body in golang. For more information, please follow other related articles on the PHP Chinese website!