Move WaitFor into new utils.go and switch timeout and interval to time.Duration.

This commit is contained in:
xenolf 2016-03-11 03:52:46 +01:00
parent 2ae35a755d
commit c50baa67cb
4 changed files with 55 additions and 44 deletions

View file

@ -8,7 +8,6 @@ import (
"log" "log"
"net" "net"
"strings" "strings"
"time"
"github.com/miekg/dns" "github.com/miekg/dns"
"golang.org/x/net/publicsuffix" "golang.org/x/net/publicsuffix"
@ -256,26 +255,3 @@ func UnFqdn(name string) string {
} }
return name return name
} }
// WaitFor polls the given function 'f', once every 'interval' seconds, up to 'timeout' seconds.
func WaitFor(timeout, interval int, f func() (bool, error)) error {
var lastErr string
timeup := time.After(time.Duration(timeout) * time.Second)
for {
select {
case <-timeup:
return fmt.Errorf("Time limit exceeded. Last error: %s", lastErr)
default:
}
stop, err := f()
if stop {
return nil
}
if err != nil {
lastErr = err.Error()
}
time.Sleep(time.Duration(interval) * time.Second)
}
}

View file

@ -163,23 +163,3 @@ func TestCheckAuthoritativeNssErr(t *testing.T) {
} }
} }
} }
func TestWaitForTimeout(t *testing.T) {
c := make(chan error)
go func() {
err := WaitFor(3, 1, func() (bool, error) {
return false, nil
})
c <- err
}()
timeout := time.After(4 * time.Second)
select {
case <-timeout:
t.Fatal("timeout exceeded")
case err := <-c:
if err == nil {
t.Errorf("expected timeout error; got %v", err)
}
}
}

29
acme/utils.go Normal file
View file

@ -0,0 +1,29 @@
package acme
import (
"fmt"
"time"
)
// WaitFor polls the given function 'f', once every 'interval' seconds, up to 'timeout' seconds.
func WaitFor(timeout, interval time.Duration, f func() (bool, error)) error {
var lastErr string
timeup := time.After(timeout * time.Second)
for {
select {
case <-timeup:
return fmt.Errorf("Time limit exceeded. Last error: %s", lastErr)
default:
}
stop, err := f()
if stop {
return nil
}
if err != nil {
lastErr = err.Error()
}
time.Sleep(interval * time.Second)
}
}

26
acme/utils_test.go Normal file
View file

@ -0,0 +1,26 @@
package acme
import (
"testing"
"time"
)
func TestWaitForTimeout(t *testing.T) {
c := make(chan error)
go func() {
err := WaitFor(3, 1, func() (bool, error) {
return false, nil
})
c <- err
}()
timeout := time.After(4 * time.Second)
select {
case <-timeout:
t.Fatal("timeout exceeded")
case err := <-c:
if err == nil {
t.Errorf("expected timeout error; got %v", err)
}
}
}