Home  >  Article  >  Backend Development  >  Asynchronous HTTP requests in Go language

Asynchronous HTTP requests in Go language

PHPz
PHPzOriginal
2023-06-02 21:10:32813browse

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!

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