How do I handle plain text HTTP Get response in Golang?

34,945

Solution 1

Response of the body can be read using any method that could read data from incoming byte stream. Simplest of them is ReadAll function provided in ioutil package.

responseData,err := ioutil.ReadAll(response.Body)
if err != nil {
    log.Fatal(err)
}

It will give you API response in []byte. If response is plain text you can easily convert it into string using type conversion:

responseString := string(responseData)

And Check the result

fmt.Println(responseString)

Sample Program:

package main

import (
    "fmt"
    "io/ioutil"
    "log"
    "net/http"
)

func main() {
    url := "http://country.io/capital.json"
    response, err := http.Get(url)
    if err != nil {
        log.Fatal(err)
    }
    defer response.Body.Close()

    responseData, err := ioutil.ReadAll(response.Body)
    if err != nil {
        log.Fatal(err)
    }

    responseString := string(responseData)

    fmt.Println(responseString)
}

Solution 2

With io.Copy you read all bytes from an io.Reader, and write it to an io.Writer

resp, err := http.Get(server.URL + "/v1/ping")
if err != nil {
    t.Errorf("failed to execute GET request: %s", err)
}
defer resp.Body.Close()

var b bytes.Buffer
if _, err := io.Copy(&b, resp.Body); err != nil {
    t.Errorf("failed to copy response body: %s", err)
}

fmt.Println(b.String())
Share:
34,945
TheJediCowboy
Author by

TheJediCowboy

I like to code...

Updated on September 06, 2020

Comments

  • TheJediCowboy
    TheJediCowboy over 3 years

    I am making an HTTP GET request to an endpoint that returns a plain text response.

    How do I grab the string of the plain text response?

    My code looks like the following:

    url := "http://someurl.com"
    
    response, err := http.Get(url)
    if err != nil {
        log.Fatal(err)
    }
    defer response.Body.Close()
    responseString := //NOT SURE HOW TO GRAB THE PLAIN TEXT STRING
    
  • Toni Villena
    Toni Villena almost 8 years
    If you get a web page with (for e.g) spanish/italian/etc. characters, you won't get a good result in conversion of []byte to string. Exactly, characters such as é, á, etc. you will get � character. You need iterate the responseData and to concat every character. An optimized way would be this ;-)
  • Toni Villena
    Toni Villena almost 8 years
    @Amd 's answer resolves the problem of Unicode text with same way my previous comment, however, I think better ;-)
  • minerva
    minerva over 2 years
    @ToniVillena "spanish/italian/etc. characters, you won't get a good result in conversion of []byte to string" — This is incorrect. If you have a valid UTF-8 byte slice, which you will if you io.ReadAll a UTF-8 encoded HTTP response, you can directly print convert []byte to string. See playground. On the other hand, if you incorrectly/manually construct a byte slice like in this example, then you will get �.