Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

rest

http

go

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 
like image 799
TheJediCowboy Avatar asked Aug 06 '16 19:08

TheJediCowboy


People also ask

How do you read HTTP response body in Golang?

To read the body of the response, we need to access its Body property first. We can access the Body property of a response using the ioutil. ReadAll() method. This method returns a body and an error.

What is HTTP request Golang?

HTTP requests are a very fundamental part of the web as a whole. They are used to access resources hosted on a server (which could be remote). HTTP is an acronym for hypertext transfer protocol, a communication protocol that ensures the transfer of data between a client and a server.

How do you send a POST request on Golang?

Go HTTP POST request FORM dataThe Content-Type header is set to application/x-www-form-urlencoded. The data is sent in the body of the request; the keys and values are encoded in key-value tuples separated by '&', with a '=' between the key and the value. We send a POST request to the https://httpbin.org/post page.


1 Answers

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) } 
like image 160
Mayank Patel Avatar answered Sep 24 '22 00:09

Mayank Patel