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>}
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.