What would be the right way to do async post and get requests?

huangapple go评论82阅读模式
英文:

What would be the right way to do async post and get requests?

问题

go的HTTP包的官方文档中提到:

> 要使用自定义标头进行请求,请使用Client.NewRequest和Client.Do

然而,如果一个POST请求需要一段时间才能完成(异步),'Client.NewRequest'和'Client.Do'会等待响应吗?

在具有自定义标头的情况下,应该如何正确地进行异步POST和GET请求?

英文:

The official docs of go's HTTP package say that

> To make a request with custom headers, use Client.NewRequest and Client.Do

However, if a post request takes time to complete (async), does 'Client.NewRequest' and 'Client.Do' await for the response?

What would be the right way to do async post and get requests while having custom headers?

答案1

得分: 1

你可以使用通道(channel)和 goroutine 来实现。

伪代码如下:

func sendRequest(resp chan *Client.Response, method, url string) {
    client := &http.Client{
        CheckRedirect: redirectPolicyFunc,
    }
    req, err := http.NewRequest(method, url, nil)
    response, err := client.Do(req)
    if err != nil {
        // 错误处理
    }
    resp <- response
}

func getResponse(resp chan *Client.Response) {
    response := <-resp
}

canal := make(chan *Client.Response)
go sendRequest(canal, "GET", "http://google.com")
go getResponse(canal)

以上代码使用了一个名为 canal 的通道(channel),并通过 sendRequest 函数发送 HTTP 请求,并将响应放入通道中。然后,通过 getResponse 函数从通道中接收响应。通过使用 goroutine,可以并发地执行这两个函数。

英文:

you can use channel and goroutine

in pseudo code:

func sendRequest(resp chan *Client.Response, method, url string) {
   client := &amp;http.Client{
	CheckRedirect: redirectPolicyFunc,
}  
   req, err := http.NewRequest(method, url, nil)
   response, err := client.Do(req)
   if err != nil {
}
   resp &lt;- response
}

func getResponse(resp chan *Client.Response) {
    response := &lt;- resp
}

canal := make(chan *Client.Response)
go sendRequest(canal, &quot;GET&quot;, &quot;http://google.com&quot;)
go getResponse(canal)

huangapple
  • 本文由 发表于 2022年9月26日 06:35:31
  • 转载请务必保留本文链接:https://go.coder-hub.com/73848243.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定