Skip to content

Commit

Permalink
fix(conn): fixed goroutine leak issue (#6)
Browse files Browse the repository at this point in the history
  • Loading branch information
cnlangzi authored Apr 19, 2024
1 parent 2cff508 commit 1ed36a0
Showing 1 changed file with 6 additions and 5 deletions.
11 changes: 6 additions & 5 deletions conn.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import (
"errors"
"net"
"net/rpc"
"sync"
"time"
)

Expand All @@ -26,24 +27,24 @@ func connect(ctx context.Context, addr string, timeout time.Duration) (*rpc.Clie
type Conn struct {
ctx context.Context
net.Conn
once sync.Once
}

func (c *Conn) wait() {
func (c *Conn) waitContext() {
// disabled deadline
c.Conn.SetReadDeadline(time.Time{}) // nolint: errcheck
c.Conn.SetDeadline(time.Time{}) // nolint: errcheck
<-c.ctx.Done()
err := c.ctx.Err()
if errors.Is(err, context.Canceled) || errors.Is(err, context.DeadlineExceeded) {
c.Conn.SetReadDeadline(time.Unix(1, 0)) // nolint: errcheck
c.Conn.SetDeadline(time.Unix(1, 0)) // nolint: errcheck
}
}

func (c *Conn) Read(p []byte) (n int, err error) {
go c.wait()
go c.once.Do(c.waitContext)
return c.Conn.Read(p)
}

func (c *Conn) Write(p []byte) (n int, err error) {
go c.wait()
return c.Conn.Write(p)
}

0 comments on commit 1ed36a0

Please sign in to comment.