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

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

How to get the body response in a request

问题

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

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

  1. request, err := http.NewRequest(method, url, nil)
  2. for k, v := range m {
  3. request.Header.Set(k, v)
  4. }
  5. if err != nil {
  6. log.Fatalln(err.Error())
  7. }
  8. client := http.Client{}
  9. resp, err := client.Do(request)
  10. if err != nil {
  11. log.Fatalln(err.Error())
  12. } else {
  13. fmt.Println("=======================")
  14. fmt.Println(resp)
  15. fmt.Println("=======================")
  16. fmt.Println(resp.Body)

然后我收到了这个:

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

  1. request, err := http.NewRequest(method, url, nil)
  2. for k, v := range m {
  3. request.Header.Set(k, v)
  4. }
  5. if err != nil {
  6. log.Fatalln(err.Error())
  7. }
  8. client := http.Client{}
  9. resp, err := client.Do(request)
  10. if err != nil {
  11. log.Fatalln(err.Error())
  12. }else{
  13. fmt.Println("=======================")
  14. fmt.Println(resp)
  15. fmt.Println("=======================")
  16. fmt.Println(resp.Body)

And i receive this:

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

答案1

得分: 10

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

  1. resp, err := http.Get("http://example.com/")
  2. if err != nil {
  3. // 处理错误
  4. }
  5. defer resp.Body.Close()
  6. 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.

  1. resp, err := http.Get("http://example.com/")
  2. if err != nil {
  3. // handle error
  4. }
  5. defer resp.Body.Close()
  6. 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:

确定