How to Read an HTTP Response Body in Go

Web
Read an HTTP response body in Go using io.ReadAll on resp.Body and ensure you defer resp.Body.Close().

Read the HTTP response body in Go by calling io.ReadAll on the resp.Body field returned by http.Get or http.Client.Do.

resp, err := http.Get("https://example.com")
if err != nil {
    log.Fatal(err)
}
defer resp.Body.Close()
body, err := io.ReadAll(resp.Body)
if err != nil {
    log.Fatal(err)
}
fmt.Println(string(body))