}
handshakeCtx, cancel := context.WithCancel(ctx)
- // Note: defer this before starting the "interrupter" goroutine
+ // Note: defer this before calling context.AfterFunc
// so that we can tell the difference between the input being canceled and
// this cancellation. In the former case, we need to close the connection.
defer cancel()
c.quic.cancelc = handshakeCtx.Done()
c.quic.cancel = cancel
} else if ctx.Done() != nil {
- // Start the "interrupter" goroutine, if this context might be canceled.
- // (The background context cannot).
- //
- // The interrupter goroutine waits for the input context to be done and
- // closes the connection if this happens before the function returns.
- done := make(chan struct{})
- interruptRes := make(chan error, 1)
+ // Close the connection if ctx is canceled before the function returns.
+ stop := context.AfterFunc(ctx, func() {
+ _ = c.conn.Close()
+ })
defer func() {
- close(done)
- if ctxErr := <-interruptRes; ctxErr != nil {
+ if !stop() {
// Return context error to user.
- ret = ctxErr
- }
- }()
- go func() {
- select {
- case <-handshakeCtx.Done():
- // Close the connection, discarding the error
- _ = c.conn.Close()
- interruptRes <- handshakeCtx.Err()
- case <-done:
- interruptRes <- nil
+ ret = ctx.Err()
}
}()
}