Golang – DumpRequest()在ReadRequest()中没有生成正确的输出吗?

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

Golang - DumpRequest() not creating correct output for ReadRequest()?

问题

创建一个字节数组的http请求,然后尝试将其读入http.request时,如果请求包含主体,则似乎无法正常工作。

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是一个空数组。

英文:

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.

答案1

得分: 4

你的代码有两个问题:

  1. 你必须处理错误。这样可以帮助你发现你从未构建过有效的请求("/Bar" 不是一个有效的 URL)。

  2. 对于发送的请求,使用 httputil.DumpRequestOut

要点:始终处理所有错误,并始终阅读整个整个包的文档。

英文:

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.

huangapple
  • 本文由 发表于 2017年3月15日 17:14:54
  • 转载请务必保留本文链接:https://go.coder-hub.com/42805424.html
匿名

发表评论

匿名网友

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

确定