fix: SetupContextForConn should return context error to user

This commit is contained in:
wwqgtxx
2025-04-10 23:32:26 +08:00
parent bfd06ebad0
commit dbb5b7db1c
3 changed files with 117 additions and 3 deletions

View File

@@ -7,7 +7,18 @@ import (
"github.com/metacubex/mihomo/common/contextutils"
)
// SetupContextForConn is a helper function that starts connection I/O interrupter goroutine.
// SetupContextForConn is a helper function that starts connection I/O interrupter.
// if ctx be canceled before done called, it will close the connection.
// should use like this:
//
// func streamConn(ctx context.Context, conn net.Conn) (_ net.Conn, err error) {
// if ctx.Done() != nil {
// done := N.SetupContextForConn(ctx, conn)
// defer done(&err)
// }
// conn, err := xxx
// return conn, err
// }
func SetupContextForConn(ctx context.Context, conn net.Conn) (done func(*error)) {
stopc := make(chan struct{})
stop := contextutils.AfterFunc(ctx, func() {
@@ -21,7 +32,7 @@ func SetupContextForConn(ctx context.Context, conn net.Conn) (done func(*error))
<-stopc
if ctxErr := ctx.Err(); ctxErr != nil && inputErr != nil {
// Return context error to user.
inputErr = &ctxErr
*inputErr = ctxErr
}
}
}