golang multiplexhttp. request. body method example

  • 2020-06-19 10:28:57
  • OfStack

Questions and scenarios

There are scenarios in the business where http.request.body need to be distributed. For example, the WeChat callback message can only specify 1 address, so you expect to be able to copy a message to another service. The WeChat callback is processed by service B and service A1 that receives the WeChat callback.

This article will introduce golang reuse http.request.body in detail, share out for your reference and study, the following words do not say much, let's have a look at the detailed introduction

solution

The first consideration was direct forwarding http.request. http. request is forwarded directly from Service A to service B using ReverseProxy. But WeChat involves validation and other issues, and it's very difficult to completely adjust it. Therefore, we change our thinking and intend to transfer the content of ES27en. request. body directly to service B.

But http.request is readcloser. When we talk about ES37en.request readAll we can't read http.request again.

How can I copy and use ES44en.request.body?

Where c represents the context of http


 //  the request The contents of 
 var bodyBytes []byte
 if c.Request.Body != nil {
  bodyBytes, _ = ioutil.ReadAll(c.Request.Body)
 }
 //  Write in what you have just read 
 c.Request.Body = ioutil.NopCloser(bytes.NewBuffer(bodyBytes))

1. We first read body from ES56en.request and saved it into a variable.

2. Then write the data in the variable back to http.request using the method ioutil.NopCloser.

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 an operateless Close method that returns an ReadCloser interface.

Then we can use c.request again for processing.

conclusion


Related articles: