Golang http.Response 全部输出:代码示例及注意事项
为了完整地输出 http.Response 的内容,我们可以使用以下代码:
func printResponse(resp *http.Response) {
fmt.Println('Status:', resp.Status)
fmt.Println('StatusCode:', resp.StatusCode)
fmt.Println('Proto:', resp.Proto)
fmt.Println('Headers:')
for key, values := range resp.Header {
for _, value := range values {
fmt.Println(key + ':', value)
}
}
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
fmt.Println('Error reading response body:', err)
return
}
fmt.Println('Body:', string(body))
resp.Body.Close()
}
然后,我们可以通过将 http.Response 对象传递给 printResponse 函数来输出完整的 http.Response 内容:
resp, err := http.Get('https://example.com')
if err != nil {
fmt.Println('Error:', err)
return
}
printResponse(resp)
这将输出 http.Response 的状态、状态码、协议、头部和主体内容。请注意,为了避免资源泄漏,我们在读取完主体内容后需要手动关闭响应的 Body。
原文地址: https://www.cveoy.top/t/topic/m620 著作权归作者所有。请勿转载和采集!