如何在请求中获取正文响应

How to get the body response in a request

我正在尝试制作一个可以像代理一样工作的网络服务器。我的服务器为客户端向特定站点发出请求(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>}

来自 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)

旁注:您也可以使用 ioutil.ReadAll 而不是 io.ReadAll,但是 ioutil 文档说:

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.