在Golang中使用http.Client.Do时出现空的HTTP响应。

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

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.

huangapple
  • 本文由 发表于 2017年3月21日 22:25:56
  • 转载请务必保留本文链接:https://go.coder-hub.com/42929882.html
匿名

发表评论

匿名网友

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

确定