!+ WaitForServer attempts to contact the server of a URL. It tries for one minute using exponential back-off. It reports an error if all attempts fail.
(url string)
| 19 | // It tries for one minute using exponential back-off. |
| 20 | // It reports an error if all attempts fail. |
| 21 | func WaitForServer(url string) error { |
| 22 | const timeout = 1 * time.Minute |
| 23 | deadline := time.Now().Add(timeout) |
| 24 | for tries := 0; time.Now().Before(deadline); tries++ { |
| 25 | _, err := http.Head(url) |
| 26 | if err == nil { |
| 27 | return nil // success |
| 28 | } |
| 29 | log.Printf("server not responding (%s); retrying...", err) |
| 30 | time.Sleep(time.Second << uint(tries)) // exponential back-off |
| 31 | } |
| 32 | return fmt.Errorf("server %s failed to respond after %s", url, timeout) |
| 33 | } |
| 34 | |
| 35 | //!- |
| 36 |