19 06 2023
在Go语言中实现异步HTTP请求有几种方法。以下是其中两种常用的方法: 1. 使用goroutine和channel: ```go package main import ( "fmt" "net/http" ) func main() { urls := []string{"http://example.com", "http://example.org"} responses := make(chan *http.Response) for _, url := range urls { go func(url string) { resp, err := http.Get(url) if err != nil { fmt.Println("Error:", err) return } responses <- resp }(url) } for i := 0; i < len(urls); i++ { resp := <-responses fmt.Println("Response:", resp.Status) resp.Body.Close() } } ``` 在这个示例中,我们使用goroutine并发地发送HTTP请求。每个goroutine都会发送请求并将响应发送到一个共享的通道(channel)中。然后,我们可以在主goroutine中通过从通道接收响应来处理它们。 2. 使用http.Client的Do方法和context.Context: ```go package main import ( "context" "fmt" "net/http" "time" ) func main() { urls := []string{"http://example.com", "http://example.org"} ctx := context.Background() ctx, cancel := context.WithTimeout(ctx, 5*time.Second) defer cancel() client := &http.Client{} for _, url := range urls { go func(url string) { req, err := http.NewRequest(http.MethodGet, url, nil) if err != nil { fmt.Println("Error:", err) return } resp, err := client.Do(req.WithContext(ctx)) if err != nil { fmt.Println("Error:", err) return } defer resp.Body.Close() fmt.Println("Response:", resp.Status) }(url) } // 等待异步请求完成 time.Sleep(6 * time.Second) } ``` 这个示例中,我们使用了`context`包来设置超时时间。每个goroutine都会创建一个HTTP请求,并通过`http.Client`的`Do`方法发送请求。我们使用`WithContext`方法将`context.Context`与请求关联起来,以便在超时或取消时终止请求。 这两种方法都可以实现异步HTTP请求,具体选择哪种方法取决于你的需求和偏好。
延伸阅读
    如何鼓励学生主动参与社区服务和公益活动?
    有哪些有趣的科学实验
    学生是否应该接受更加国际化的历史教育?
    正骨师要考什么证
    如何鼓励学生主动参与课外活动和社团组织?