Initial commit

This commit is contained in:
Nise Void 2020-08-06 11:41:26 +02:00
commit d28e60d19f
Signed by: NiseVoid
GPG Key ID: FBA14AC83EA602F3
2 changed files with 83 additions and 0 deletions

25
waitfor.go Normal file
View File

@ -0,0 +1,25 @@
package waitfor
import (
"net"
"time"
)
func Try(network, address string, interval, limit time.Duration) bool {
start := time.Now()
for {
if limit >= 0 && time.Since(start) > limit {
return false
}
attempt := time.Now()
conn, err := net.DialTimeout(network, address, interval)
if err != nil {
time.Sleep(time.Until(attempt.Add(interval)))
continue
}
conn.Close()
return true
}
}

58
waitfor_test.go Normal file
View File

@ -0,0 +1,58 @@
package waitfor
import (
"net"
"testing"
"time"
"git.fuyu.moe/Fuyu/assert"
)
func TestDeadline(t *testing.T) {
assert := assert.New(t)
start := time.Now()
ok := Try(`tcp`, `127.0.0.1:65398`, time.Microsecond*100, time.Millisecond)
assert.False(ok)
assert.Eq(int64(1), time.Since(start).Milliseconds())
start = time.Now()
ok = Try(`tcp`, `127.0.0.1:65398`, time.Microsecond*100, 0)
assert.False(ok)
assert.Eq(int64(0), time.Since(start).Milliseconds())
}
func TestSuccess(t *testing.T) {
assert := assert.New(t)
conn, err := net.Listen(`tcp`, `127.0.0.1:65398`)
assert.NoError(err)
defer conn.Close()
start := time.Now()
ok := Try(`tcp`, `127.0.0.1:65398`, time.Microsecond*100, time.Millisecond*10)
assert.True(ok)
assert.True(time.Since(start).Milliseconds() < 10)
}
func TestInfiniteLimit(t *testing.T) {
assert := assert.New(t)
var conn net.Listener
go func() {
time.Sleep(time.Millisecond)
var err error
conn, err = net.Listen(`tcp`, `127.0.0.1:65398`)
assert.NoError(err)
}()
start := time.Now()
ok := Try(`tcp`, `127.0.0.1:65398`, time.Microsecond*100, time.Millisecond*-1)
assert.True(ok)
assert.True(time.Since(start).Milliseconds() < 2)
conn.Close()
}