Use the http.Get function to send a GET request and obtain the response status code and response content length
In the Go language, we can use the http.Get function provided by the http package to send a GET request. Through the GET request, we can obtain the response status code returned by the server and the length of the response content. Let's take a look at the specific implementation process.
First, in our Go code, we need to import the net/http package to use the http.Get function. The code is as follows:
package main import ( "fmt" "net/http" ) func main() { // 发送GET请求 resp, err := http.Get("http://www.example.com") if err != nil { fmt.Println("发送GET请求失败:", err) return } defer resp.Body.Close() // 获取响应状态码 statusCode := resp.StatusCode fmt.Println("响应状态码:", statusCode) // 获取响应内容长度 contentLength := resp.ContentLength if contentLength == -1 { fmt.Println("响应内容长度未知") } else { fmt.Println("响应内容长度:", contentLength) } }
In the above code, we sent a GET request to "http://www.example.com" through the http.Get function, and assigned the response result to the resp variable . At the same time, we use the defer keyword to ensure that the response Body is closed before the function returns to prevent resource leaks.
Next, we use resp.StatusCode to get the response status code and print it out. The response status code represents the server's processing result of the request. It is usually a three-digit integer. For example, 200 indicates that the request was successful, and 404 indicates that the page was not found.
Finally, we use resp.ContentLength to get the length of the response content and print it out. ContentLength returns an int64 type value, indicating the size of the response content. It should be noted that some servers may not provide the Content-Length field in the response header. In this case, ContentLength will return -1, indicating that the response content length is unknown.
With the above code, we can send a GET request and obtain the response status code and response content length. You can modify the code as needed to suit your actual needs. Hope this article is helpful to you!
The above is the detailed content of Use the http.Get function to send a GET request and obtain the response status code and response content length.. For more information, please follow other related articles on the PHP Chinese website!