Use the net/http.Head function to send a HEAD request and get the response status code
In the Go language, we can use the functions provided by the net/http package to send HTTP requests and process HTTP responses. Among them, the Head function can send a HEAD request and return the response status code.
The following is a sample code that shows how to use the net/http.Head function to send a HEAD request and get the response status code:
package main import ( "fmt" "net/http" ) func main() { // 创建一个http.Client client := &http.Client{} // 创建一个HEAD请求 req, err := http.NewRequest("HEAD", "https://www.example.com", nil) if err != nil { fmt.Println("创建请求失败:", err) return } // 发送请求 resp, err := client.Do(req) if err != nil { fmt.Println("发送请求失败:", err) return } defer resp.Body.Close() // 获取响应状态码 statusCode := resp.StatusCode fmt.Println("响应状态码:", statusCode) }
In the above sample code, we first create a http.Client, and then uses the http.NewRequest function to create a HEAD request object. Next, we sent the request through the client.Do method and got the response object resp. Finally, we get the response status code through resp.StatusCode and print it out.
It should be noted that the request address in the above code is "https://www.example.com", you can replace it with the specific target URL.
Through the above code example, we can easily use the Head function of the net/http package to send a HEAD request and obtain the response status code. This is very useful in some scenarios where we only care about service availability, response time and other information.
The above is the detailed content of Use the net/http.Head function to send a HEAD request and get the response status code. For more information, please follow other related articles on the PHP Chinese website!