Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Go output with ioutil: returning array of (ASCII?) numbers from http call

Tags:

http

go

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

like image 619
Clay Shirky Avatar asked Sep 13 '25 04:09

Clay Shirky


1 Answers

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
like image 150
icza Avatar answered Sep 14 '25 17:09

icza