Advertisement
Guest User

Untitled

a guest
Jul 8th, 2019
308
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. /*The httpDo function runs the HTTP request and processes its response in a new goroutine. It cancels the request if ctx.Done is closed before the goroutine exits:*/
  2.  
  3. func httpDo(ctx context.Context, req *http.Request, f func(*http.Response, error) error) error {
  4.     // Run the HTTP request in a goroutine and pass the response to f.
  5.     c := make(chan error, 1)
  6.     req = req.WithContext(ctx)
  7.     go func() { c <- f(http.DefaultClient.Do(req)) }()
  8.     select {
  9.     case <-ctx.Done():
  10.         <-c // Wait for f to return.
  11.         return ctx.Err()
  12.     case err := <-c:
  13.         return err
  14.     }
  15. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement