首頁 > 後端開發 > Golang > 主體

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

DDD
發布: 2024-11-15 08:22:02
原創
452 人瀏覽過

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中文網其他相關文章!

來源:php.cn
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板