How to Retrieve Plain Text Responses from HTTP GET Requests in Golang
A frequently encountered task when working with HTTP requests is handling plain text responses. In Golang, retrieving this text requires specific steps. Consider the following scenario:
url := "http://someurl.com"<br>response, err := http.Get(url)<br>if err != nil {</p><div class="code" style="position:relative; padding:0px; margin:0px;"><pre class="brush:php;toolbar:false">log.Fatal(err)
}
defer response.Body.Close()
// How to grab the plain text response?
To access the plain text response, follow these steps:
1. Read the Response Body
Utilize the ioutil.ReadAll function to read the entire response body into a byte array:
responseData, err := ioutil.ReadAll(response.Body) if err != nil { log.Fatal(err) }
2. Convert Response Bytes to String
Since the response is plain text, convert the byte array to a string:
responseString := string(responseData)
3. Check the Result
Display the retrieved plain text response string for confirmation:
fmt.Println(responseString)
Sample Code:
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) }
The above is the detailed content of How to Extract Plain Text from HTTP GET Responses in Golang?. For more information, please follow other related articles on the PHP Chinese website!