Last active
July 20, 2022 08:12
-
-
Save sivsivsree/c53c6db8a57f704cc1d3ce8d967d58bc to your computer and use it in GitHub Desktop.
This file contains hidden or 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
func main() { | |
// creating parent context | |
ctx, cancel := context.WithCancel(context.Background()) | |
defer cancel() | |
// this is for graceful shutdown | |
exit := make(chan os.Signal, 1) | |
signal.Notify(exit, os.Interrupt, syscall.SIGTERM) | |
for { | |
select { | |
case <-exit: | |
cancel() | |
fmt.Println("shutting down gracefully.") | |
case <-ctx.Done(): | |
// listens for parent context cancellation | |
fmt.Println("parent context is cancelled.") | |
os.Exit(0) | |
default: | |
// calls our service check every one second. | |
time.Sleep(1 * time.Second) | |
if serviceHealthCheck(ctx, "https://google.com") { | |
fmt.Println("Service OK") | |
} else { | |
fmt.Println("Service Fail") | |
} | |
} | |
} | |
} | |
// serviceHealthCheck is a very dumb healthcheck which | |
// takes an url and return true if able to get the url | |
// in the specified context timout duration else false. | |
func serviceHealthCheck(ctx context.Context, url string) bool { | |
status := make(chan bool, 1) | |
// create a new context with parent ctx and provide timeout duration | |
// you can also use context.WithDeadline as follows. | |
//ctx, cancel := context.WithDeadline(ctx, time.Now().Add(700*time.Millisecond)) | |
ctx, cancel := context.WithTimeout(ctx, 700*time.Millisecond) | |
defer cancel() | |
// dummy implementation of service health check | |
go func(url string) { | |
client := http.Client{} | |
if _, err := client.Get(url); err != nil { | |
status <- false | |
} | |
status <- true | |
}(url) | |
select { | |
case s := <-status: | |
return s | |
case <-ctx.Done(): | |
fmt.Println("request timeout") | |
return false | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment