How to Handle Plain Text HTTP GET Responses in Golang?

Patricia Arquette
Release: 2024-11-11 15:14:02
Original
805 people have browsed it

How to Handle Plain Text HTTP GET Responses in Golang?

Handling Plain Text HTTP GET Response in Golang

In Golang, retrieving the response body of an HTTP GET request is straightforward. However, if the response is in plain text, it can be challenging to grab the string representation.

To resolve this issue, the first step is to acquire the response body using the ioutil.ReadAll function from the ioutil package:

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

This function reads all the data from the response body and stores it in a []byte slice. For plain text responses, the slice can be directly converted to a string:

responseString := string(responseData)
Copy after login

Here's an example program to demonstrate the process:

package main

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

func main() {
    url := "http://someurl.com"
    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

Running this program will print the plain text response returned by the GET request.

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