Skip to content

Commit

Permalink
Add (*Client).RunContext to allow for cancelation
Browse files Browse the repository at this point in the history
Refs #42

This is the first step towards actual Context support in this library.
Next steps may involve passing a Context around with each message and
adding support to callbacks.
  • Loading branch information
belak committed Apr 10, 2018
1 parent a6af4ab commit 3a984a1
Showing 1 changed file with 15 additions and 3 deletions.
18 changes: 15 additions & 3 deletions client.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package irc

import (
"context"
"errors"
"fmt"
"io"
Expand Down Expand Up @@ -357,6 +358,12 @@ func (c *Client) startReadLoop(wg *sync.WaitGroup) {
// strange and unexpected ways if it is called again before the first connection
// exits.
func (c *Client) Run() error {
return c.RunContext(context.TODO())
}

// RunContext is the same as Run but a context.Context can be passed in for
// cancelation.
func (c *Client) RunContext(ctx context.Context) error {
// exiting is used by the main goroutine here to ensure any sub-goroutines
// get closed when exiting.
exiting := make(chan struct{})
Expand All @@ -382,9 +389,14 @@ func (c *Client) Run() error {
// messages.
c.startReadLoop(&wg)

// Wait for an error from any goroutine, then signal we're exiting and wait
// for the goroutines to exit.
err := <-c.errChan
// Wait for an error from any goroutine or for the context to time out, then
// signal we're exiting and wait for the goroutines to exit.
var err error
select {
case err = <-c.errChan:
case <-ctx.Done():
}

close(exiting)
wg.Wait()

Expand Down

0 comments on commit 3a984a1

Please sign in to comment.