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)
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)
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) }
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!