Home >Backend Development >Golang >Use the net/http.Get function to send a GET request and get the response status code

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

王林
王林Original
2023-07-25 11:37:231321browse

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

In the Go language, we can use the net/http package to send HTTP requests. Among them, the Get function can be used to send a GET request and return a *http.Response type response object.

The following is a sample code that demonstrates how to use the Get function to send a GET request and get the response status code.

package main

import (
    "fmt"
    "net/http"
)

func main() {
    url := "https://www.example.com" // 替换为你要请求的URL

    resp, err := http.Get(url)
    if err != nil {
        fmt.Println("发送GET请求失败:", err)
        return
    }
    defer resp.Body.Close()

    fmt.Println("响应状态码:", resp.StatusCode)
}

In the above code, we first define a url variable to store the target URL to which we want to send a GET request. Please replace the value of this variable with the URL you actually want to request.

Then, we use the http.Get function to send a GET request and assign the returned response object to the resp variable. If the request fails to be sent, an error message will be output on the console and the program will exit.

Next, we use the defer keyword to ensure that the response body is closed at the end of the function. Finally, we print the StatusCode attribute of the response object, which is the response status code.

Please note that the two packages fmt and net/http are used in the above code. You need to add the corresponding import statement at the top of the code file:

package main

import (
    "fmt"
    "net/http"
)

// ...

Run the above code, you will see the output response status code, indicating whether the request was successful. You can perform further processing based on different status codes.

Summary

This article introduces how to use the net/http.Get function to send a GET request and obtain the response status code. You only need to provide the target URL and determine the success or failure of the request based on the response status code for subsequent processing. I hope this article can help you better understand and use the HTTP request function in Go language.

The above is the detailed content of Use the net/http.Get function to send a GET 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