Home > Backend Development > Golang > How Do I Access an HTTP Response Body as a String in Go?

How Do I Access an HTTP Response Body as a String in Go?

DDD
Release: 2024-12-08 07:24:16
Original
347 people have browsed it

How Do I Access an HTTP Response Body as a String in Go?

Accessing HTTP Response as a String in Go

When parsing the response of a web request, accessing it as a string can be problematic. Consider the following code:

resp, err := http.Get("http://google.hu/")
if err != nil {
    // handle error
}
defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)
Copy after login

While the code successfully fetches the response body, attempting to iterate over it as a string using for i:= 0; i < len(body); i { fmt.Println( body[i] ) } yields numerical values instead of characters.

The key to accessing the response as a string lies in a simple conversion:

bs := string(body)
Copy after login

This conversion treats the byte slice body as a sequence of Unicode code points and creates a corresponding string. Once converted, you can manipulate bs like any other string.

For example, the following code demonstrates the conversion and subsequent string manipulation:

var client http.Client
resp, err := client.Get(url)
if err != nil {
    log.Fatal(err)
}
defer resp.Body.Close()

if resp.StatusCode == http.StatusOK {
    bodyBytes, err := io.ReadAll(resp.Body)
    if err != nil {
        log.Fatal(err)
    }
    bodyString := string(bodyBytes)
    fmt.Println(bodyString)
}
Copy after login

This conversion highlights the distinction between bytes and strings in Go. Strings are immutable sequences of Unicode code points, while byte slices are mutable sequences of raw bytes. The conversion from a byte slice to a string effectively creates a new string that represents the sequence of characters encoded by the bytes.

The above is the detailed content of How Do I Access an HTTP Response Body as 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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template