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

How to Read Plain Text HTTP GET Responses in Golang?

DDD
Release: 2024-11-15 08:22:02
Original
537 people have browsed it

How to Read Plain Text HTTP GET Responses in Golang?

Handling Plain Text HTTP GET Responses in Golang

When working with HTTP GET requests that return plain text responses, understanding how to access the string representation of the response is crucial. This guide explains how to grab the plain text string from an HTTP GET response using Golang.

To access the plain text response, you can utilize the ReadAll function provided by the ioutil package. This function reads all remaining data from the response body and returns it as a byte array ([]byte).

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

Since the response is plain text, you can easily convert the byte array to a string using type conversion:

responseString := string(responseData)
Copy after login

To verify the result, you can print the response string:

fmt.Println(responseString)
Copy after login

Sample Program:

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

By following this approach, you can effectively handle plain text HTTP GET responses and access their string representations in your Golang applications.

The above is the detailed content of How to Read Plain Text 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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template