Skip to content

Commit 2a61dc3

Browse files
committed
Add (*Client).RunContext to allow for cancelation
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.
1 parent a6af4ab commit 2a61dc3

File tree

1 file changed

+15
-3
lines changed

1 file changed

+15
-3
lines changed

client.go

+15-3
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
package irc
22

33
import (
4+
"context"
45
"errors"
56
"fmt"
67
"io"
@@ -357,6 +358,12 @@ func (c *Client) startReadLoop(wg *sync.WaitGroup) {
357358
// strange and unexpected ways if it is called again before the first connection
358359
// exits.
359360
func (c *Client) Run() error {
361+
return c.RunContext(context.TODO())
362+
}
363+
364+
// RunContext is the same as Run but a context.Context can be passed in for
365+
// cancelation.
366+
func (c *Client) RunContext(ctx context.Context) error {
360367
// exiting is used by the main goroutine here to ensure any sub-goroutines
361368
// get closed when exiting.
362369
exiting := make(chan struct{})
@@ -382,9 +389,14 @@ func (c *Client) Run() error {
382389
// messages.
383390
c.startReadLoop(&wg)
384391

385-
// Wait for an error from any goroutine, then signal we're exiting and wait
386-
// for the goroutines to exit.
387-
err := <-c.errChan
392+
// Wait for an error from any goroutine or for the context to time out, then
393+
// signal we're exiting and wait for the goroutines to exit.
394+
var err error
395+
select {
396+
case err = <-c.errChan:
397+
case <-ctx.Done():
398+
}
399+
388400
close(exiting)
389401
wg.Wait()
390402

0 commit comments

Comments
 (0)