登录
首页 >  Golang >  Go问答

将 cURL 请求转换为 http.Request

来源:stackoverflow

时间:2024-04-07 21:06:34 242浏览 收藏

小伙伴们有没有觉得学习Golang很有意思?有意思就对了!今天就给大家带来《将 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, err := http.NewRequest("GET", "http://localhost:81/" + url.QueryEscape("Hallo"), nil)
    client := &http.Client{}
    resp, err := client.Do(request)

如果我运行 go 代码(我尝试了测试),它只会产生此错误:i 仅收到错误 net/http: http/1.x 传输连接损坏:格式错误的 http 状态代码“-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 响应代码)

理论要掌握,实操不能落!以上关于《将 cURL 请求转换为 http.Request》的详细介绍,大家都掌握了吧!如果想要继续提升自己的能力,那么就来关注golang学习网公众号吧!

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>