2023-01-23 18:54:21 +07:00
|
|
|
/*
|
|
|
|
* SPDX-License-Identifier: AGPL-3.0-only
|
2024-01-04 16:28:16 +07:00
|
|
|
* Copyright (c) 2022-2024, daeuniverse Organization <dae@v2raya.org>
|
2023-01-23 18:54:21 +07:00
|
|
|
*/
|
|
|
|
|
2023-02-08 19:15:24 +07:00
|
|
|
package netutils
|
2023-01-23 18:54:21 +07:00
|
|
|
|
|
|
|
import (
|
|
|
|
"context"
|
|
|
|
"net"
|
|
|
|
)
|
|
|
|
|
|
|
|
type ContextDialer struct {
|
2023-02-17 23:49:35 +07:00
|
|
|
Dialer net.Dialer
|
2023-01-23 18:54:21 +07:00
|
|
|
}
|
|
|
|
|
|
|
|
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
|
|
|
|
}
|
|
|
|
}
|