简体   繁体   English

如何在 Golang 中处理纯文本 HTTP Get 响应?

[英]How do I handle plain text HTTP Get response in Golang?

I am making an HTTP GET request to an endpoint that returns a plain text response.我正在向返回纯文本响应的端点发出 HTTP GET 请求。

How do I grab the string of the plain text response?如何获取纯文本响应的字符串?

My code looks like the following:我的代码如下所示:

url := "http://someurl.com"

response, err := http.Get(url)
if err != nil {
    log.Fatal(err)
}
defer response.Body.Close()
responseString := //NOT SURE HOW TO GRAB THE PLAIN TEXT STRING

Response of the body can be read using any method that could read data from incoming byte stream.可以使用任何可以从传入字节流中读取数据的方法读取主体的响应。 Simplest of them is ReadAll function provided in ioutil package.其中最简单的是 ioutil 包中提供的 ReadAll 函数。

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

It will give you API response in []byte.它将以 [] 字节为您提供 API 响应。 If response is plain text you can easily convert it into string using type conversion:如果响应是纯文本,您可以使用类型转换轻松将其转换为字符串:

responseString := string(responseData)

And Check the result并检查结果

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

Use ioutil.ReadAll(response.Body) .使用ioutil.ReadAll(response.Body)

Also you may handle Unicode text using bufio.NewScanner(response.Body)您也可以使用bufio.NewScanner(response.Body)处理 Unicode 文本
like this working sample code:像这个工作示例代码:

package main

import (
    "bufio"
    "bytes"
    "fmt"
    "log"
    "net/http"
)

func main() {
    response, err := http.Get("http://127.0.0.1")
    if err != nil {
        log.Fatal(err)
    }
    defer response.Body.Close()

    scanner := bufio.NewScanner(response.Body)
    scanner.Split(bufio.ScanRunes)
    var buf bytes.Buffer
    for scanner.Scan() {
        buf.WriteString(scanner.Text())
    }
    fmt.Println(buf.String())
}

output:输出:

*Hello World* B=µH *

Using this sample web server code:使用此示例 Web 服务器代码:

package main

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

func ServeHTTP(w http.ResponseWriter, r *http.Request) {
    body := "*Hello World* B=µH *"
    fmt.Fprint(w, body)
}

func main() {
    http.HandleFunc("/", ServeHTTP)
    if err := http.ListenAndServe(":80", nil); err != nil {
        log.Fatal(err)
    }
}

With io.Copy you read all bytes from an io.Reader, and write it to an io.Writer使用io.Copyio.Copy读取所有字节,并将其写入 io.Writer

resp, err := http.Get(server.URL + "/v1/ping")
if err != nil {
    t.Errorf("failed to execute GET request: %s", err)
}
defer resp.Body.Close()

var b bytes.Buffer
if _, err := io.Copy(&b, resp.Body); err != nil {
    t.Errorf("failed to copy response body: %s", err)
}

fmt.Println(b.String())

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM