http - 将 cURL 请求转换为 http.Request
问题描述
这个 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,如下所示:
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/生成的)
谁能帮我理解为什么这两个请求会产生不同的结果?
解决方案
对真实服务器的示例请求和响应:
[@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 响应代码)
推荐阅读
- python - 如何防止 TypeError:+ 不支持的操作数类型:“NoneType”和“float”
- c - Printf 格式说明符
- .net - 我在 NET 5 中使用 Vue js 向控制器发送 ID,但结果为空
- javascript - javascript中的异步和等待
- prolog - 如何编写谓词来检查两个相同的 X 值是否有不同的 Y 值?
- android - liftOnScroll 不适用于 NestedScrollView
- rust - 使用了函数`print`,但为什么它警告我`unused`?
- algorithm - 在透视模仿上均匀排列线条的公式?
- python - django-allauth 信号 user_signed_in 信号不起作用
- csv - 编写一个 lambda 函数来检索存储在 AWS S3 中的 CSV 文件