Skip to content

Commit

Permalink
add ErrOSTimeout
Browse files Browse the repository at this point in the history
  • Loading branch information
egoroof committed May 5, 2024
1 parent 112c413 commit be7aafa
Showing 1 changed file with 14 additions and 2 deletions.
16 changes: 14 additions & 2 deletions pkg/ping/net.go
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ import (
)

var ErrInvalidResponse = errors.New("invalid response")
var ErrOSTimeout = errors.New("OS goes sleep and causes timeout")

type ServerResponse struct {
Name string
Expand All @@ -19,8 +20,10 @@ type ServerResponse struct {
}

func OpenConnection(name, host string, port, timeout int, respose chan<- ServerResponse) {
timeoutDuration := time.Millisecond * time.Duration(timeout)

address := fmt.Sprintf("%v:%v", host, port)
conn, err := net.DialTimeout("tcp", address, time.Millisecond*time.Duration(timeout))
conn, err := net.DialTimeout("tcp", address, timeoutDuration)
if err != nil {
respose <- ServerResponse{
Name: name,
Expand All @@ -31,7 +34,7 @@ func OpenConnection(name, host string, port, timeout int, respose chan<- ServerR
defer conn.Close()

buf := make([]byte, 4)
conn.SetDeadline(time.Now().Add(time.Millisecond * time.Duration(timeout)))
conn.SetDeadline(time.Now().Add(timeoutDuration))
connectTime := time.Now()
_, err = conn.Read(buf)
duration := time.Since(connectTime)
Expand Down Expand Up @@ -62,6 +65,15 @@ func OpenConnection(name, host string, port, timeout int, respose chan<- ServerR
return
}

// OS can goes sleep
if duration > timeoutDuration {
respose <- ServerResponse{
Name: name,
Error: ErrOSTimeout,
}
return
}

respose <- ServerResponse{
Name: name,
Duration: int(duration.Milliseconds()),
Expand Down

0 comments on commit be7aafa

Please sign in to comment.