dae/common/netutils/context_dialer.go

40 lines
637 B
Go
Raw Normal View History

2023-01-23 18:54:21 +07:00
/*
* SPDX-License-Identifier: AGPL-3.0-only
* Copyright (c) since 2023, mzz2017 <mzz@tuta.io>
2023-01-23 18:54:21 +07:00
*/
package netutils
2023-01-23 18:54:21 +07:00
import (
"context"
"golang.org/x/net/proxy"
"net"
)
type ContextDialer struct {
Dialer proxy.Dialer
}
func (d *ContextDialer) DialContext(ctx context.Context, network, addr string) (c net.Conn, err error) {
var done = make(chan struct{})
go func() {
c, err = d.Dialer.Dial(network, addr)
if err != nil {
close(done)
return
}
select {
case <-ctx.Done():
_ = c.Close()
default:
close(done)
}
}()
select {
case <-ctx.Done():
return nil, ctx.Err()
case <-done:
return c, err
}
}