使用 Go 發送異步 HTTP 請求

做法

新增 main.go 檔。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
package main

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

func main() {
var wg sync.WaitGroup
urls := []string{
"https://json.epoch.tw/api/records/GELe31Mb69",
"https://json.epoch.tw/api/records/KGRb4x1bBL",
"https://json.epoch.tw/api/records/qM7e5yBe2v",
}

// 建立 channel 用來傳遞 API 的回應
responses := make(chan *http.Response)

// 遍歷 urls 並平行發送 HTTP 請求
for _, url := range urls {
wg.Add(1)
go func(url string) {
defer wg.Done()

resp, err := http.Get(url)
if err != nil {
fmt.Println(err)
return
}

responses <- resp
}(url)
}

// 當所有 goroutine 都完成時,關閉 channel
go func() {
wg.Wait()
close(responses)
}()

// 遍歷 API 的回應並印出結果
for resp := range responses {
fmt.Println("Response received:", resp.Status)
}
}

執行程式。

1
go run main.go

輸出如下:

1
2
3
Response received: 200 OK
Response received: 200 OK
Response received: 200 OK