Fix: use the fastest whether the result is successful

This commit is contained in:
Dreamacro
2020-02-14 16:36:20 +08:00
parent 6641bf7c07
commit 8b5e511426
5 changed files with 30 additions and 63 deletions

View File

@ -20,7 +20,22 @@ func (c *client) Exchange(m *D.Msg) (msg *D.Msg, err error) {
func (c *client) ExchangeContext(ctx context.Context, m *D.Msg) (msg *D.Msg, err error) {
c.Client.Dialer = dialer.Dialer()
// Please note that miekg/dns ExchangeContext doesn't respond to context cancel.
msg, _, err = c.Client.ExchangeContext(ctx, m, c.Address)
return
// miekg/dns ExchangeContext doesn't respond to context cancel.
// this is a workaround
type result struct {
msg *D.Msg
err error
}
ch := make(chan result, 1)
go func() {
msg, _, err := c.Client.ExchangeContext(ctx, m, c.Address)
ch <- result{msg, err}
}()
select {
case <-ctx.Done():
return nil, ctx.Err()
case ret := <-ch:
return ret.msg, ret.err
}
}