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

Patricia Arquette
Release: 2024-11-11 00:03:03
Original
422 people have browsed it

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><div class="code" style="position:relative; padding:0px; margin:0px;"><pre class="brush:php;toolbar:false">log.Fatal(err)
Copy after login

}
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)
}
Copy after login

2. Convert Response Bytes to String

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

responseString := string(responseData)
Copy after login

3. Check the Result

Display the retrieved plain text response string for confirmation:

fmt.Println(responseString)
Copy after login

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)
}
Copy after login

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!

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 Recommendations
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template