Asynchronous HTTP requests in Go language
In today's Internet era, many applications need to make network requests to obtain or send data. HTTP requests are one of the most commonly used network request methods. In the Go language, we can use the net/http package in the standard library to initiate HTTP requests, but this will block the current coroutine. So how to implement asynchronous HTTP requests in Go language? This article will introduce two methods of implementing asynchronous HTTP requests in the Go language.
Method 1: Using goroutine and channel
Goroutine allows us to easily implement asynchronous programming, and channel can facilitate communication between coroutines. Therefore, we can initiate an HTTP request in a goroutine and then use a channel to pass the response back to the main goroutine. The following is a simple example:
func asyncHTTP(url string, ch chan<- []byte) { resp, err := http.Get(url) if err != nil { log.Fatal(err) } defer resp.Body.Close() body, err := ioutil.ReadAll(resp.Body) if err != nil { log.Fatal(err) } ch <- body } func main() { ch := make(chan []byte) url := "https://www.example.com" go asyncHTTP(url, ch) fmt.Println("Waiting for response...") responseBody := <-ch fmt.Println("Received response:", string(responseBody)) }
In the above example, we first create a ch (type chan []byte) to pass the response result back to the main coroutine. Then we call the asyncHTTP
function to initiate an HTTP request, which will write the response result into ch. Finally, we read the response result from ch by using the <-ch
operator.
It should be noted that if the HTTP request is not initiated through goroutine, then the operation of reading the response result <-ch
will cause the current coroutine to block. Using goroutine and channels allows us to easily implement asynchronous HTTP requests.
Method 2: Using context and http.Do
In the Go language, we can use the context package to control the execution time and cancellability of the function. Using context in conjunction with the http.Do function, we can implement cancelable asynchronous HTTP requests. The following is a simple example:
func asyncHTTPWithCtx(ctx context.Context, url string) ([]byte, error) { req, err := http.NewRequestWithContext(ctx, http.MethodGet, url, nil) if err != nil { return nil, err } client := http.DefaultClient resp, err := client.Do(req) if err != nil { return nil, err } defer resp.Body.Close() body, err := ioutil.ReadAll(resp.Body) if err != nil { return nil, err } return body, nil } func main() { ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) defer cancel() url := "https://www.example.com" resp, err := asyncHTTPWithCtx(ctx, url) if err != nil { log.Fatal(err) } fmt.Println("Response:", string(resp)) }
In the above example, we use the context.WithTimeout
function to create a cancelable context. Then we called the asyncHTTPWithCtx
function, which uses the http.Do function to initiate an HTTP request. The http.Do function can accept a context parameter. When the context is canceled, the http.Do function will cancel the executing HTTP request.
It should be noted that when using the http.Do function, we must manually close the response body. Otherwise, this may lead to resource leaks or connection pool exhaustion. Therefore, in the asyncHTTPWithCtx
function, we use a defer statement to ensure that the response body is closed when the function returns.
Summary
This article introduces two methods of implementing asynchronous HTTP requests in the Go language: using goroutine and channel and using context and http.Do function. The method using goroutine and channel is a more general method and can be used to asynchronously request any type of network resource. The method of using context and http.Do functions is more suitable for scenarios where request cancellation needs to be controlled. Using these technologies, we can easily implement asynchronous HTTP requests, improving application performance and responsiveness.
The above is the detailed content of Asynchronous HTTP requests in Go language. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



The library used for floating-point number operation in Go language introduces how to ensure the accuracy is...

Queue threading problem in Go crawler Colly explores the problem of using the Colly crawler library in Go language, developers often encounter problems with threads and request queues. �...

Which libraries in Go are developed by large companies or well-known open source projects? When programming in Go, developers often encounter some common needs, ...

The difference between string printing in Go language: The difference in the effect of using Println and string() functions is in Go...

Two ways to define structures in Go language: the difference between var and type keywords. When defining structures, Go language often sees two different ways of writing: First...

Go pointer syntax and addressing problems in the use of viper library When programming in Go language, it is crucial to understand the syntax and usage of pointers, especially in...

The problem of using RedisStream to implement message queues in Go language is using Go language and Redis...

Why does map iteration in Go cause all values to become the last element? In Go language, when faced with some interview questions, you often encounter maps...
