[networking] Access HTTP response as string in Go

I'd like to parse the response of a web request, but I'm getting trouble accessing it as string.

func main() {
    resp, err := http.Get("http://google.hu/")
    if err != nil {
        // handle error
    }
    defer resp.Body.Close()
    body, err := ioutil.ReadAll(resp.Body)

    ioutil.WriteFile("dump", body, 0600)

    for i:= 0; i < len(body); i++ {
        fmt.Println( body[i] ) // This logs uint8 and prints numbers
    }

    fmt.Println( reflect.TypeOf(body) )
    fmt.Println("done")
}

How can I access the response as string? ioutil.WriteFile writes correctly the response to a file.

I've already checked the package reference but it's not really helpful.

This question is related to networking go

The answer is


The method you're using to read the http body response returns a byte slice:

func ReadAll(r io.Reader) ([]byte, error)

official documentation

You can convert []byte to a string by using

body, err := ioutil.ReadAll(resp.Body)
bodyString := string(body)

string(byteslice) will convert byte slice to string, just know that it's not only simply type conversion, but also memory copy.