Home Backend Development Golang Asynchronous HTTP requests in Go language

Asynchronous HTTP requests in Go language

Jun 02, 2023 pm 09:10 PM
go language http request Asynchronous request

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))
}
Copy after login

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))
}
Copy after login

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 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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

What libraries are used for floating point number operations in Go? What libraries are used for floating point number operations in Go? Apr 02, 2025 pm 02:06 PM

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

What is the problem with Queue thread in Go's crawler Colly? What is the problem with Queue thread in Go's crawler Colly? Apr 02, 2025 pm 02:09 PM

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 provided by well-known open source projects? Which libraries in Go are developed by large companies or provided by well-known open source projects? Apr 02, 2025 pm 04:12 PM

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, ...

In Go, why does printing strings with Println and string() functions have different effects? In Go, why does printing strings with Println and string() functions have different effects? Apr 02, 2025 pm 02:03 PM

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

What is the difference between `var` and `type` keyword definition structure in Go language? What is the difference between `var` and `type` keyword definition structure in Go language? Apr 02, 2025 pm 12:57 PM

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...

Why is it necessary to pass pointers when using Go and viper libraries? Why is it necessary to pass pointers when using Go and viper libraries? Apr 02, 2025 pm 04:00 PM

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...

How to solve the user_id type conversion problem when using Redis Stream to implement message queues in Go language? How to solve the user_id type conversion problem when using Redis Stream to implement message queues in Go language? Apr 02, 2025 pm 04:54 PM

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

Why do all values ​​become the last element when using for range in Go language to traverse slices and store maps? Why do all values ​​become the last element when using for range in Go language to traverse slices and store maps? Apr 02, 2025 pm 04:09 PM

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...

See all articles