Accessing HTTP Response as String in Go
Accessing HTTP response as string in Go can be achieved using a straightforward method. Here's how you can do it:
In your example code, the issue lies in the handling of the response body. To access it as a string, you need to convert the byte slice ([]byte) returned by ioutil.ReadAll to a string using the string function:
bs := string(body)
Once you have the response body as a string, you can manipulate it like any other regular string. Here's an example:
resp, err := http.Get("http://google.hu/") if err != nil { // Handle error } defer resp.Body.Close() body, err := io.ReadAll(resp.Body) if err != nil { // Handle error } respString := string(body) fmt.Println(respString) // Prints the response body as a string if strings.Contains(respString, "html") { // Check if the response contains "html" }
It's important to note that this conversion is not as efficient as working with the byte slice directly. If you don't need to specifically access the response as a string, it's better to keep it as a byte slice and work with it in that form.
The above is the detailed content of How to Access an HTTP Response Body as a String in Go?. For more information, please follow other related articles on the PHP Chinese website!