Go语言教程之边写边学:使用HTTP客户端从HTTP响应中读取标头
在Go中,您可以使用http从HTTP客户端的HTTP响应中读取标头。响应类型。下面是如何从HTTP响应中读取标头的示例:
package main
import (
"fmt"
"net/http"
)
func main() {
// Create an HTTP client
client := &http.Client{}
// Send an HTTP request
resp, err := client.Get("https://example.com")
if err != nil {
fmt.Println("Error sending HTTP request:", err)
return
}
defer resp.Body.Close()
// Read headers from the HTTP response
contentType := resp.Header.Get("Content-Type")
server := resp.Header.Get("Server")
// Print headers
fmt.Println("Content-Type:", contentType)
fmt.Println("Server:", server)
}
在此示例中,我们使用http.client发送HTTP请求。Get方法。然后,我们使用resp.Header.Get方法从HTTP响应中读取标头。
在此示例中,我们读取了两个标头:"Content-Type"标头和"Server"标头。我们使用fmt.Println将这些标头打印到控制台。
需要注意的是,http.响应类型还提供了更多用于处理HTTP响应的方法,例如获取状态代码、读取响应正文以及一次获取多个标头的值。
系列文章