How does Go language achieve concurrent requests?

The Go language can achieve concurrent requests by using goroutines and channels. Here is a simple example:

package main

import (
	"fmt"
	"net/http"
	"time"
)

func main() {
	// 创建一个通道,用于接收请求结果
	results := make(chan string)

	// 定义一组URL
	urls := []string{
		"https://www.google.com",
		"https://www.baidu.com",
		"https://www.github.com",
	}

	// 遍历URL,为每个URL启动一个goroutine进行并行请求
	for _, url := range urls {
		go request(url, results)
	}

	// 等待所有请求完成,并收集结果
	for i := 0; i < len(urls); i++ {
		result := <-results
		fmt.Println(result)
	}
}

func request(url string, results chan<- string) {
	// 发送HTTP GET请求
	resp, err := http.Get(url)
	if err != nil {
		results <- fmt.Sprintf("Error requesting %s: %s", url, err)
		return
	}
	defer resp.Body.Close()

	// 模拟处理响应的延迟
	time.Sleep(time.Second)

	// 读取响应内容
	results <- fmt.Sprintf("Request to %s completed with status code %d", url, resp.StatusCode)
}

In the example above, we created a channel called results to receive the results of requests. We then defined a set of URLs and used the go keyword to start a group of goroutines to send requests in parallel. Each goroutine executes the request function, which sends an HTTP GET request and sends the response to the results channel.

Finally, we use a loop to wait for all requests to finish and collect the results from the results channel. This way, we can send multiple requests in parallel and handle the results once all requests are completed.

bannerAds