client: break out recv into loop and recv (#115)

This isolates the use of broadcastErr from the normal recv/lookup loop.
This commit is contained in:
Dave Cheney 2016-06-15 17:58:19 +10:00 committed by GitHub
parent 7d4fc94878
commit a3218d2747
1 changed files with 12 additions and 8 deletions

View File

@ -76,7 +76,7 @@ func NewClientPipe(rd io.Reader, wr io.WriteCloser, opts ...func(*Client) error)
return nil, err return nil, err
} }
sftp.wg.Add(1) sftp.wg.Add(1)
go sftp.recv() go sftp.loop()
return sftp, nil return sftp, nil
} }
@ -154,16 +154,21 @@ func (c *Client) broadcastErr(err error) {
} }
} }
func (c *Client) loop() {
defer c.wg.Done()
err := c.recv()
if err != nil {
c.broadcastErr(err)
}
}
// recv continuously reads from the server and forwards responses to the // recv continuously reads from the server and forwards responses to the
// appropriate channel. // appropriate channel.
func (c *Client) recv() { func (c *Client) recv() error {
defer c.wg.Done()
for { for {
typ, data, err := c.recvPacket() typ, data, err := c.recvPacket()
if err != nil { if err != nil {
// Return the error to all listeners. return err
c.broadcastErr(err)
return
} }
sid, _ := unmarshalUint32(data) sid, _ := unmarshalUint32(data)
c.mu.Lock() c.mu.Lock()
@ -174,8 +179,7 @@ func (c *Client) recv() {
// This is an unexpected occurrence. Send the error // This is an unexpected occurrence. Send the error
// back to all listeners so that they terminate // back to all listeners so that they terminate
// gracefully. // gracefully.
c.broadcastErr(errors.Errorf("sid: %v not fond", sid)) return errors.Errorf("sid: %v not fond", sid)
return
} }
ch <- result{typ: typ, data: data} ch <- result{typ: typ, data: data}
} }