Home  >  Article  >  Backend Development  >  Use the net/http.Head function to send a HEAD request and get the response status code

Use the net/http.Head function to send a HEAD request and get the response status code

WBOY
WBOYOriginal
2023-07-25 12:29:111548browse

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn