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
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)
}
Use ioutil.ReadAll(response.Body)
.
Also you may handle Unicode text using bufio.NewScanner(response.Body)
like this working sample code:
package main
import (
"bufio"
"bytes"
"fmt"
"log"
"net/http"
)
func main() {
response, err := http.Get("http://127.0.0.1")
if err != nil {
log.Fatal(err)
}
defer response.Body.Close()
scanner := bufio.NewScanner(response.Body)
scanner.Split(bufio.ScanRunes)
var buf bytes.Buffer
for scanner.Scan() {
buf.WriteString(scanner.Text())
}
fmt.Println(buf.String())
}
output:
*Hello World* B=µH *
Using this sample web server code:
package main
import (
"fmt"
"log"
"net/http"
)
func ServeHTTP(w http.ResponseWriter, r *http.Request) {
body := "*Hello World* B=µH *"
fmt.Fprint(w, body)
}
func main() {
http.HandleFunc("/", ServeHTTP)
if err := http.ListenAndServe(":80", nil); err != nil {
log.Fatal(err)
}
}
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())