Home  >  Article  >  Backend Development  >  How to Extract Plain Text from HTTP GET Responses in Golang?

How to Extract Plain Text from HTTP GET Responses in Golang?

Patricia Arquette
Patricia ArquetteOriginal
2024-11-11 00:03:03447browse

How to Extract Plain Text from HTTP GET Responses in Golang?

How to Retrieve Plain Text Responses from HTTP GET Requests in Golang

A frequently encountered task when working with HTTP requests is handling plain text responses. In Golang, retrieving this text requires specific steps. Consider the following scenario:

url := "http://someurl.com"<br>response, err := http.Get(url)<br>if err != nil {</p><pre class="brush:php;toolbar:false">log.Fatal(err)

}
defer response.Body.Close()

// How to grab the plain text response?

To access the plain text response, follow these steps:

1. Read the Response Body

Utilize the ioutil.ReadAll function to read the entire response body into a byte array:

responseData, err := ioutil.ReadAll(response.Body)
if err != nil {
    log.Fatal(err)
}

2. Convert Response Bytes to String

Since the response is plain text, convert the byte array to a string:

responseString := string(responseData)

3. Check the Result

Display the retrieved plain text response string for confirmation:

fmt.Println(responseString)

Sample Code:

package main

import (
    "fmt"
    "io/ioutil"
    "log"
    "net/http"
)

func main() {
    url := "http://country.io/capital.json"
    response, err := http.Get(url)
    if err != nil {
        log.Fatal(err)
    }
    defer response.Body.Close()

    responseData, err := ioutil.ReadAll(response.Body)
    if err != nil {
        log.Fatal(err)
    }

    responseString := string(responseData)

    fmt.Println(responseString)
}

The above is the detailed content of How to Extract Plain Text from HTTP GET Responses in Golang?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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