Home > Software design >  What would be the right way to do async post and get requests?
What would be the right way to do async post and get requests?

Time:09-29

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?

CodePudding user response:

you can use channel and goroutine

in pseudo code:

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)
  •  Tags:  
  • go
  • Related