-
Notifications
You must be signed in to change notification settings - Fork 30
/
Copy pathdialer.go
50 lines (41 loc) · 1.16 KB
/
dialer.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
package dial
import (
"net"
)
// Dialer is used to test connections
type Dialer struct {
semaphore chan struct{}
}
// Status saves information about connection
type Status struct {
Ok bool
Err error
}
// NewDialer returns pointer to new Dialer
func NewDialer(concurrentConnections int) *Dialer {
return &Dialer{
semaphore: make(chan struct{}, concurrentConnections),
}
}
// NewWorker is used to send address over NetAddressTimeout to make request and receive status over DialerStatus
// Blocks until slot in semaphore channel for concurrency is free
func (d *Dialer) NewWorker() (chan<- NetAddressTimeout, <-chan Status) {
netAddressTimeoutCh := make(chan NetAddressTimeout)
dialerStatusCh := make(chan Status)
d.semaphore <- struct{}{}
go func() {
netAddressTimeout := <-netAddressTimeoutCh
conn, err := net.DialTimeout(netAddressTimeout.Network, netAddressTimeout.Address, netAddressTimeout.Timeout)
dialerStatus := Status{}
if err != nil {
dialerStatus.Ok = false
dialerStatus.Err = err
} else {
dialerStatus.Ok = true
conn.Close()
}
dialerStatusCh <- dialerStatus
<-d.semaphore
}()
return netAddressTimeoutCh, dialerStatusCh
}