Home > Backend Development > Golang > How to Convert an HTTP Response Body to a String in Go?

How to Convert an HTTP Response Body to a String in Go?

Linda Hamilton
Release: 2024-12-02 16:34:16
Original
647 people have browsed it

How to Convert an HTTP Response Body to a String in Go?

Accessing HTTP Response as a String in Go

When attempting to parse the response of a web request as a string in Go, you may encounter difficulties due to the response being stored as a slice of bytes. To resolve this issue and access the response as a string, follow the steps below:

1. Read the HTTP Response Body:

func main() {
    resp, err := http.Get("http://google.hu/")
    if err != nil {
        // handle error
    }
    defer resp.Body.Close()

    bodyBytes, err := io.ReadAll(resp.Body)
    if err != nil {
        // handle error
    }
}
Copy after login

2. Convert the Byte Slice to a String:

To convert the slice of bytes to a string, you can use type conversion:

bodyString := string(bodyBytes)
Copy after login

3. Utilize the String:

Once you have converted the byte slice to a string, you can manipulate it as a regular string in Go. For example, you can print it to the console or perform string operations.

Example:

fmt.Println(bodyString)
Copy after login

This code will output the response body as a string.

Note:

It's important to note that converting a byte slice to a string in Go involves allocating memory on the heap due to the immutability of strings. Therefore, it's recommended to perform operations on the byte slice as much as possible before converting it to a string for memory efficiency.

The above is the detailed content of How to Convert an HTTP Response Body to a String in Go?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template