如何在请求中获取响应体。

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

How to get the body response in a request

问题

我正在尝试创建一个像代理一样工作的Web服务器。我的服务器向客户端发送请求(POST、GET...)到特定的网站,接收来自该网站的响应并将其返回给客户端。就像一个代理一样。问题是:例如来自google.com(或任何其他网站)的响应中,我无法读取正文内容。状态码是200,但当我尝试读取正文内容时,我收到了奇怪的东西。

这是我发送请求的代码部分:

request, err := http.NewRequest(method, url, nil)
for k, v := range m {
    request.Header.Set(k, v)
}
if err != nil {
    log.Fatalln(err.Error())
}

client := http.Client{}
resp, err := client.Do(request)

if err != nil {
    log.Fatalln(err.Error())
} else {

fmt.Println("=======================")
fmt.Println(resp)
fmt.Println("=======================")
fmt.Println(resp.Body)

然后我收到了这个:

=======================
&{200 OK 200 HTTP/1.1 1 1 map[Date:[Mon, 09 Jan 2017 18:07:49 GMT]
Cache-Control:[private, max-age=0] Content-Type:[text/html; 
charset=ISO-8859-1] P3p:[CP="This is not a P3P policy! See 
https://www.google.com/support/accounts/answer/151657?hl=en for more 
info."] Server:[gws] X-Xss-Protection:[1; mode=block] Expires:[-1] X-
Frame-Options:[SAMEORIGIN] Set-Cookie:[NID=94=i5qZWuqYtrLAkc-amGHbmDnqx3Wg8mGx0kuk6s-
gKWYMSNXbScl0Cb5GldDzGdfrIrJvHC3151JzHB2s3XLdmFN82-
_gSxu07xwPNbVlzKiZgE9dJf7vXeXSaYQhWowv; expires=Tue, 11-Jul-2017 
18:07:49 GMT; path=/; domain=.google.com.br; HttpOnly]] 0xc4200cac20 
-1 [] false true map[] 0xc420126000 <nil>}
=======================
&{0xc420014700 <nil> <nil>}
英文:

I'm trying to make a webserver that will work like a proxy. My server make requests (POST, GET ...) for the client to an specific site, receive the response from this site and give it to the client. As i said, like a proxy. The problem is: in the response from google.com for example (or any other site) i can't read the body. The status code is 200 but when i tried to read the body content i receive weird things.

This is the part of my code that i make the request

request, err := http.NewRequest(method, url, nil)
for k, v := range m {
	request.Header.Set(k, v)
}
if err != nil {
	log.Fatalln(err.Error())
}

client := http.Client{}
resp, err := client.Do(request)

if err != nil {
	log.Fatalln(err.Error())
}else{

fmt.Println("=======================")
fmt.Println(resp)
fmt.Println("=======================")
fmt.Println(resp.Body)

And i receive this:

=======================
&{200 OK 200 HTTP/1.1 1 1 map[Date:[Mon, 09 Jan 2017 18:07:49 GMT]
Cache-Control:[private, max-age=0] Content-Type:[text/html; 
charset=ISO-8859-1] P3p:[CP="This is not a P3P policy! See 
https://www.google.com/support/accounts/answer/151657?hl=en for more 
info."] Server:[gws] X-Xss-Protection:[1; mode=block] Expires:[-1] X-
Frame-Options:[SAMEORIGIN] Set-Cookie:[NID=94=i5qZWuqYtrLAkc-amGHbmDnqx3Wg8mGx0kuk6s-
gKWYMSNXbScl0Cb5GldDzGdfrIrJvHC3151JzHB2s3XLdmFN82-
_gSxu07xwPNbVlzKiZgE9dJf7vXeXSaYQhWowv; expires=Tue, 11-Jul-2017 
18:07:49 GMT; path=/; domain=.google.com.br; HttpOnly]] 0xc4200cac20 
-1 [] false true map[] 0xc420126000 <nil>}
=======================
&{0xc420014700 <nil> <nil>}

答案1

得分: 10

从https://golang.org/pkg/net/http的文档中,要读取响应的主体,可以使用io.ReadAll

resp, err := http.Get("http://example.com/")
if err != nil {
        // 处理错误
}
defer resp.Body.Close()
body, err := io.ReadAll(resp.Body)

顺便提一下:你也可以使用ioutil.ReadAll代替io.ReadAll,但是ioutil的文档中说:

> 从Go 1.16开始,相同的功能现在由io包或os包提供,应该在新代码中优先使用这些实现。

英文:

From the documentation at https://golang.org/pkg/net/http, to read the body of the response you can use io.ReadAll.

resp, err := http.Get("http://example.com/")
if err != nil {
        // handle error
}
defer resp.Body.Close()
body, err := io.ReadAll(resp.Body)

Side note: You can also use ioutil.ReadAll instead of io.ReadAll, but the ioutil documentation says:

> As of Go 1.16, the same functionality is now provided by package io or package os, and those implementations should be preferred in new code.

huangapple
  • 本文由 发表于 2017年1月10日 02:22:33
  • 转载请务必保留本文链接:https://go.coder-hub.com/41554423.html
匿名

发表评论

匿名网友

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

确定