Rumah >pembangunan bahagian belakang >Golang >Bagaimana untuk Membaca Teks Biasa HTTP GET Responses di Golang?

Bagaimana untuk Membaca Teks Biasa HTTP GET Responses di Golang?

DDD
DDDasal
2024-11-15 08:22:02539semak imbas

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

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

responseString := string(responseData)

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

fmt.Println(responseString)

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

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

Atas ialah kandungan terperinci Bagaimana untuk Membaca Teks Biasa HTTP GET Responses di Golang?. Untuk maklumat lanjut, sila ikut artikel berkaitan lain di laman web China PHP!

Kenyataan:
Kandungan artikel ini disumbangkan secara sukarela oleh netizen, dan hak cipta adalah milik pengarang asal. Laman web ini tidak memikul tanggungjawab undang-undang yang sepadan. Jika anda menemui sebarang kandungan yang disyaki plagiarisme atau pelanggaran, sila hubungi admin@php.cn