英文:
Empty HTTP Response Using http.Client.Do in Golang
问题
我正在使用Go语言进行HTTP GET请求,请求一个外部Web服务。但是,无论什么原因,响应的主体始终为空,内容长度始终为零字节。然而,响应的状态码始终为200,而且调用Client.Do没有返回任何错误。该请求需要一个Authorization头部,所以我使用http.NewRequest / http.Client.Do模式来提交请求,如下所示。过去我也做过类似的请求,但从未使用需要头部的GET请求。这似乎不太可能是问题的原因,但我想知道是否可能有关。如果有人能发现使用的模式中的潜在问题,或者有类似的经验,我将非常感激任何帮助。
谢谢。
if req, err := http.NewRequest("GET", "https://api.molt.in/v1/orders/11111111/items", nil); err != nil {
return nil, err
} else {
client := &http.Client{}
req.Header.Add("Authorization", "secretToken")
if resp, err := client.Do(req); err != nil {
return nil, err
} else {
defer resp.Body.Close()
return readBody(resp.Body)
}
}
英文:
I am using Go to make an HTTP GET request to an external web service. For some reason, the body of the response is always empty; the content length is always zero bytes. The response status code is always 200, however, and the call to Client.Do returns no error. The request requires an Authorization header, so I am using the http.NewRequest / http.Client.Do pattern to submit the request, as you'll see below. I have done requests similar to these in the past, but never using a GET that required a header. It seems unlikely that this the cause, but I wonder if it may be related. If anyone can spot any potential issues with the pattern used or perhaps has had a similar experience, I'd really appreciate any help.
Thank you.
if req, err := http.NewRequest("GET", "https://api.molt.in/v1/orders/11111111/items", nil); err != nil {
return nil, err
} else {
client := &http.Client{}
req.Header.Add("Authorization", "secretToken")
if resp, err := client.Do(req); err != nil {
return nil, err
} else {
defer resp.Body.Close()
return readBody(resp.Body)
}
}
答案1
得分: 1
我终于找到了问题的源头。它与请求的发出或接收到的响应无关,而是与响应的解析有关。
我之前使用了bufio.NewScanner.Text来尝试将响应体转换为字符串。将这个调用替换为ioutil.ReadAll后,输出了我最初期望的字符串。
感谢你的帮助,对于给你带来的误导性问题我表示道歉。
英文:
I finally discovered the source of the problem. It had nothing to do with the request being made, or the response being received. It had to do with the parsing of the response.
I was using bufio.NewScanner.Text to attempt to convert the response body into a string. Replacing this call with one to ioutil.ReadAll output the string that I originally expected.
Thanks for all of your help, and apologies for the misleading question.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论