Home >Backend Development >Golang >How to Handle Plain Text HTTP GET Responses in Go?

How to Handle Plain Text HTTP GET Responses in Go?

Patricia Arquette
Patricia ArquetteOriginal
2024-11-10 01:50:02697browse

How to Handle Plain Text HTTP GET Responses in Go?

Handling Plain Text HTTP GET Responses in Go

When making an HTTP GET request to an endpoint that returns a plain text response, retrieving the text can be achieved through a combination of the ioutil package and type conversion.

In your given code:

url := "http://someurl.com"

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

The response body contains the plain text response, but it is in the form of a byte array. To obtain the string representation, use the ioutil.ReadAll function to read the entire body into a []byte slice:

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

Finally, since the response is plain text, it can be easily converted to a string using type conversion:

responseString := string(responseData)

This completes the process of handling plain text HTTP GET responses in Go. The resulting responseString variable now contains the plain text response as a string.

Example Program:

package main

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

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

    // Retrieve plain text response
    responseData, err := ioutil.ReadAll(response.Body)
    if err != nil {
        log.Fatal(err)
    }
    responseString := string(responseData)

    // Print result
    fmt.Println(responseString)
}

The above is the detailed content of How to Handle Plain Text HTTP GET Responses in Go?. 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