Golang-DumpRequest()没有为ReadRequest()创建正确的输出?

Creating a byte array of a http request and then trying to read it into a http.request doesn't seem to work when the request includes a body.

req, _ := http.NewRequest(http.MethodPost, "/Bar", strings.NewReader("Foo"))
rReq, _ := httputil.DumpRequest(req, true)

req2, _ := http.ReadRequest(bufio.NewReader(bytes.NewReader(rReq)))
b, _ := ioutil.ReadAll(req2.Body)
fmt.Println(b)

b is an empty array.

Two things are wrong in your code:

  1. You must handle the errors. This would have helpesd you see that you never construct a valid request ("/Bar" is not a valid URL).

  2. Use httputil.DumpRequestOut for outgoing request.

Takeaways: Always handle all errors and always read the whole whole package doc.