Created
March 8, 2021 17:54
-
-
Save Harsimran1/d73f0cb6e4b54f9467481b9599570a96 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"errors" | |
"net/http" | |
"time" | |
) | |
// makeRequest makes simple http request and returns an error channel | |
func makeRequest() <-chan error { | |
// create a buffered error channel | |
errChan := make(chan error, 1) | |
// initiate a request in a new go routine. | |
// this is done so that the request can keep on happening without cancellation | |
// in case there is no response from the http call | |
// within the designated time. | |
go func() { | |
resp, err := http.Get("https://medium.com") | |
// on receiving the response of http call, we send signal to channel | |
// that the response has been received. | |
errChan <- err | |
defer resp.Body.Close() | |
}() | |
return errChan | |
} | |
func makeRequestWithTimeout(waitTime time.Duration) error { | |
timeout := time.After(waitTime * time.Second) | |
// wait for either the timeout to happen or getting the response from makeRequest func | |
// return value is defined based on whatever happens first. | |
select { | |
case <-timeout: | |
return errors.New("wait time exceeded, processing will still run in the background") | |
case err := <-makeRequest(): | |
return err | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment