Send GET request and get response using http.Get function in golang

WBOY
Release: 2023-11-18 11:32:22
Original
1431 people have browsed it

Send GET request and get response using http.Get function in golang

Use the http.Get function in golang to send a GET request and get the response

When using golang for network programming, we often need to send HTTP requests and get the response result. Golang's standard library provides a powerful and easy-to-use http package, whose Get function can help us send GET requests and get responses.

First, we need to import the required packages:

import "net/http"
import "fmt"
import "io/ioutil"
Copy after login

Next, we can use the http.Get function to send a GET request and get the response result. The following is a simple example:

func main() {
    // 发送GET请求
    response, err := http.Get("https://jsonplaceholder.typicode.com/posts")
    if err != nil {
        fmt.Printf("发送GET请求失败:%s
", err)
        return
    }

    // 延迟关闭响应体
    defer response.Body.Close()

    // 读取响应体内容
    body, err := ioutil.ReadAll(response.Body)
    if err != nil {
        fmt.Printf("读取响应体内容失败:%s
", err)
        return
    }

    // 将响应体内容转换为字符串并输出
    fmt.Println(string(body))
}
Copy after login

In the above code, we send a GET request through the http.Get function and assign the response result to the response variable. Use the defer keyword to ensure that the response body is closed before the function ends.

Next, we use the ioutil.ReadAll function to read the content of the response body and assign it to the body variable. Finally, we convert the response body content into a string and output it using the fmt.Println function.

It should be noted that in actual development, we may also need to handle errors in the process of sending requests and processing responses, as well as judge the status code of the response, etc. But the above example is a simple example for everyone to quickly get started using the http.Get function to send a GET request and get the response.

Summary:

In this article, we introduced how to use the http.Get function in golang to send a GET request and get the response. Through this simple yet powerful function, we can easily send HTTP requests and get the response results from the server. I hope this article will be helpful to your study.

The above is the detailed content of Send GET request and get response using http.Get function in golang. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template