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

How to Process Plain Text HTTP GET Responses in Golang?

Susan Sarandon
Susan SarandonOriginal
2024-11-10 10:39:02886browse

How to Process Plain Text HTTP GET Responses in Golang?

Processing Plain Text HTTP GET Responses in Golang

When sending HTTP GET requests that return plain text responses, capturing the text can be a stumbling block. Here's a definitive guide on how to retrieve the plain text in Golang:

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

要点:

  1. Use ioutil.ReadAll: The 'ioutil' package provides a convenient function for reading data from an input stream. In this case, we use ioutil.ReadAll to read the entire response.
  2. Convert to String: The data read from the response body is of type []byte. To obtain the actual plain text, we convert it to a string using type conversion.
  3. Sample Program: The provided code demonstrates how to send an HTTP GET request, read and convert the plain text response, and print it to the console.

By following these steps, you can efficiently process plain text HTTP GET responses in Golang, enabling you to further work with the textual data as needed in your application.

The above is the detailed content of How to Process Plain Text 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