I am trying to write a web client in Go, but when I check the return value of the body of the http request, I get an array of numbers, instead of text.
This is the most isolated version of the program that produces the output. I think I am failing do something with ioutil, but do not know what.
package main
import "fmt"
import "net/http"
import "io/ioutil"
func main() {
resp, err := http.Get("http://test.com/")
if err != nil {
fmt.Println(err)
}
defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)
fmt.Print(body)
}
The output comes out looking like:
[239 187 191 60 33 68 79 67 84 89 80 69 32 104 116 109 108 ...
instead of the test returned by test.com
ioutil.ReadAll()
returns a byte slice ([]byte
) and not a string
(plus an error
).
Convert it to string
and you're good to go:
fmt.Print(string(body))
See this simple example (try it on Go Playground):
var b []byte = []byte("Hello")
fmt.Println(b)
fmt.Println(string(b))
Output:
[72 101 108 108 111]
Hello