Created
January 22, 2015 02:35
-
-
Save sym3tri/cf0f345dabc330dd604b to your computer and use it in GitHub Desktop.
simple go app to check the health of a url then do stuff if unhealthy
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 ( | |
"flag" | |
"fmt" | |
"log" | |
"net/http" | |
"os" | |
"time" | |
) | |
const ( | |
checkInterval = time.Second * 30 | |
maxSleep = time.Minute * 5 | |
) | |
func main() { | |
fs := flag.NewFlagSet("sidekick-flagset", flag.ExitOnError) | |
healthURL := fs.String("health-url", "", "health url to check") | |
etcdURL := fs.String("etcd-url", "http://localhost:4001", "etcd api endpoint") | |
if err := fs.Parse(os.Args[1:]); err != nil { | |
fmt.Fprintln(os.Stderr, err.Error()) | |
os.Exit(1) | |
} | |
if *healthURL == "" { | |
fmt.Fprintln(os.Stderr, "health-url is required") | |
os.Exit(1) | |
} | |
fmt.Printf("started using: etcd-url=%s, health-url=%s\n", *etcdURL, *healthURL) | |
var sleep time.Duration | |
for { | |
if HealthCheck(*healthURL) { | |
sleep = checkInterval | |
fmt.Printf("healthy, retrying in: %v\n", sleep) | |
} else { | |
sleep = ExpBackoff(sleep, maxSleep) | |
log.Printf("Unhealthy, retrying in: %v\n", sleep) | |
DoStuff() | |
} | |
time.Sleep(sleep) | |
} | |
} | |
func DoStuff() { | |
fmt.Println("stuff") | |
} | |
func HealthCheck(url string) bool { | |
resp, err := http.Get(url) | |
if err != nil { | |
log.Printf("Error during health check: %v", err) | |
return false | |
} | |
if resp.StatusCode == http.StatusOK { | |
return true | |
} | |
return false | |
} | |
func ExpBackoff(prev, max time.Duration) time.Duration { | |
if prev == 0 { | |
return time.Second | |
} | |
if prev > max/2 { | |
return max | |
} | |
return 2 * prev | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment