resthttpgo

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


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

Solution

  • 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 io package.

    responseData,err := io.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"
        "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 := io.ReadAll(response.Body)
        if err != nil {
            log.Fatal(err)
        }
    
        responseString := string(responseData)
    
        fmt.Println(responseString)
    }