首頁 >後端開發 >Golang >如何在 Golang 中讀取純文字 HTTP GET 回應?

如何在 Golang 中讀取純文字 HTTP GET 回應?

DDD
DDD原創
2024-11-15 08:22:02555瀏覽

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.

以上是如何在 Golang 中讀取純文字 HTTP GET 回應?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn