将 cURL 请求转换为 http.Request

时间:2020-12-24 17:35:12

标签: http go curl

这个 cURL 命令应该如何工作:

curl -i -v  http://localhost:81/hallo
*   Trying ::1...
* TCP_NODELAY set
* Connected to localhost (::1) port 81 (#0)
> GET /hallo HTTP/1.1
> Host: localhost:81
> User-Agent: curl/7.55.1
> Accept: */*
>
1 -1 0* Connection #0 to host localhost left intact

现在我尝试在我的 go-service 中执行相同的 http 请求,如下所示:

request, err := http.NewRequest("GET", "http://localhost:81/" + url.QueryEscape("Hallo"), nil)
    client := &http.Client{}
    resp, err := client.Do(request)

如果我运行 go 代码(我通过测试尝试过)它只会产生这个错误:I only get the error net/http: HTTP/1.x transport connection broken: malformed HTTP status code "-1"。 (我最初尝试 http.Get(myurl)。这会产生相同的 http 请求。当前代码由 https://mholt.github.io/curl-to-go/ 生成)

谁能帮我理解为什么这两个请求会产生不同的结果?

1 个答案:

答案 0 :(得分:2)

对真正服务器的请求和响应示例:

[@xxxx ~]# curl -v -i 10.103.118.178:40000/ready
* About to connect() to 10.103.118.178 port 40000 (#0)
*   Trying 10.103.118.178...
* Connected to 10.103.118.178 (10.103.118.178) port 40000 (#0)
> GET /ready HTTP/1.1
> User-Agent: curl/7.29.0
> Host: 10.103.118.178:40000
> Accept: */*
>
< HTTP/1.1 200 OK
HTTP/1.1 200 OK
< date: Fri, 25 Dec 2020 01:43:05 GMT
date: Fri, 25 Dec 2020 01:43:05 GMT
< content-length: 2
content-length: 2
< content-type: text/plain; charset=utf-8
content-type: text/plain; charset=utf-8

<
* Connection #0 to host 10.103.118.178 left intact
ok

您使用 -i 告诉 curl 在输出中包含标题。但是,我在 curl 输出中看不到任何有效的 HTTP 响应标头。所以可能您的服务器出现故障并且没有做出有效的 HTTP 响应。所以 Go 程序正确地报告了这一点,它不能将其解释为有效的 HTTP 标头。 (它试图将其解释为 HTTP 响应标头,但在应该出现状态代码的地方,它发现 -1 不是有效的 HTTP 响应代码)