📟 在Go中转换HTTP响应io.ReadCloser为字符串

1,016 阅读1分钟

当你向服务器发送HTTP请求时,你经常想读取响应的内容。在Go中,响应的主体可以在 Response.Body的字段中找到。 http.Response对象中找到,它是HTTP客户端发送请求的结果。Go中的HTTP响应体的类型是 io.ReadCloser.要将该 io.ReadCloser对象转换为字符串,你需要使用函数读取这个字段的内容。 io.ReadAll()函数读取这个字段的内容。

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
package main
import (
"fmt"
"io"
"log"
"net/http"
)
func main() {
client := &http.Client{}
req, err := http.NewRequest(http.MethodGet, "https://example.com/", nil)
if err != nil {
log.Fatal(err)
}
resp, err := client.Do(req)
if err != nil {
log.Fatal(err)
}
bytes, err := io.ReadAll(resp.Body)
if err != nil {
log.Fatal(err)
}
fmt.Println(string(bytes))
}

在上面的例子中,我们正在向example.com/网站发出一个标准的GET 请求。在21 ,我们用函数读取响应体。 io.ReadAll()函数读取响应体。这个函数将读取的响应体作为一个字节片返回,所以为了打印它,我们需要将它转换为一个字符串。

作为这个例子的输出,你将看到example.com/网站的HTML内容。

<!doctype html>
<html>
<head>
<title>Example Domain</title>
<meta charset="utf-8" />
<meta http-equiv="Content-type" content="text/html; charset=utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<style type="text/css">
body {
background-color: #f0f0f2;
margin: 0;
padding: 0;
font-family: -apple-system, system-ui, BlinkMacSystemFont, "Segoe UI", "Open Sans", "Helvetica Neue", Helvetica, Arial, sans-serif;
}
div {
width: 600px;
margin: 5em auto;
padding: 2em;
background-color: #fdfdff;
border-radius: 0.5em;
box-shadow: 2px 3px 7px 2px rgba(0,0,0,0.02);
}
a:link, a:visited {
color: #38488f;
text-decoration: none;
}
@media (max-width: 700px) {
div {
margin: 0 auto;
width: auto;
}
}
</style>
</head>
<body>
<div>
<h1>Example Domain</h1>
<p>This domain is for use in illustrative examples in documents. You may use this
domain in literature without prior coordination or asking for permission.</p>
<p><a href="https://www.iana.org/domains/example">More information...</a></p>
</div>
</body>
</html>