英文:
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
你的代码有两个问题:
-
你必须处理错误。这样可以帮助你发现你从未构建过有效的请求("/Bar" 不是一个有效的 URL)。
-
对于发送的请求,使用
httputil.DumpRequestOut
。
要点:始终处理所有错误,并始终阅读整个整个包的文档。
英文:
Two things are wrong in your code:
-
You must handle the errors. This would have helpesd you see that you never construct a valid request ("/Bar" is not a valid URL).
-
Use
httputil.DumpRequestOut
for outgoing request.
Takeaways: Always handle all errors and always read the whole whole package doc.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论