Home > Article > Backend Development > How to Handle Plain Text HTTP GET Responses in Golang?
Handling Plain Text HTTP GET Response in Golang
In Golang, retrieving the response body of an HTTP GET request is straightforward. However, if the response is in plain text, it can be challenging to grab the string representation.
To resolve this issue, the first step is to acquire the response body using the ioutil.ReadAll function from the ioutil package:
responseData,err := ioutil.ReadAll(response.Body) if err != nil { log.Fatal(err) }
This function reads all the data from the response body and stores it in a []byte slice. For plain text responses, the slice can be directly converted to a string:
responseString := string(responseData)
Here's an example program to demonstrate the process:
package main import ( "fmt" "io/ioutil" "log" "net/http" ) func main() { url := "http://someurl.com" 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) }
Running this program will print the plain text response returned by the GET request.
The above is the detailed content of How to Handle Plain Text HTTP GET Responses in Golang?. For more information, please follow other related articles on the PHP Chinese website!