main.go 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. // pollEndpoint is a helper utility that waits for a http endpoint to be reachable and return with http.StatusOK
  2. package main
  3. import (
  4. "flag"
  5. "fmt"
  6. "io/ioutil"
  7. "net/http"
  8. "net/url"
  9. "os"
  10. "time"
  11. "github.com/cryptix/go/logging"
  12. )
  13. var (
  14. endpoint = flag.String("ep", "http://127.0.0.1:5001/version", "which http endpoint path to hit")
  15. tries = flag.Int("tries", 10, "how many tries to make before failing")
  16. timeout = flag.Duration("tout", time.Second, "how long to wait between attempts")
  17. log logging.Interface
  18. check = logging.CheckFatal
  19. )
  20. func main() {
  21. flag.Parse()
  22. logging.SetupLogging(nil)
  23. log = logging.Logger("pollEndpoint")
  24. // construct url to dial
  25. u, err := url.Parse(*endpoint)
  26. check(err)
  27. // show what we got
  28. start := time.Now()
  29. log.Log("event", "starting", "ties", *tries, "timeout", *timeout, "url", u.String())
  30. for *tries > 0 {
  31. err := checkOK(http.Get(u.String()))
  32. if err == nil {
  33. log.Log("event", "reachable", "left", *tries, "took", time.Since(start))
  34. os.Exit(0)
  35. }
  36. log.Log("event", "reqFailed", "err", err)
  37. time.Sleep(*timeout)
  38. *tries--
  39. }
  40. log.Log("event", "failed")
  41. os.Exit(1)
  42. }
  43. func checkOK(resp *http.Response, err error) error {
  44. if err == nil { // request worked
  45. defer resp.Body.Close()
  46. if resp.StatusCode == http.StatusOK {
  47. return nil
  48. }
  49. body, err := ioutil.ReadAll(resp.Body)
  50. if err != nil {
  51. fmt.Fprintf(os.Stderr, "pollEndpoint: ioutil.ReadAll() Error: %s", err)
  52. }
  53. return fmt.Errorf("Response not OK. %d %s %q", resp.StatusCode, resp.Status, string(body))
  54. }
  55. return err
  56. }