github.com/metacubex/mihomo@v1.18.5/common/net/context.go (about) 1 package net 2 3 import ( 4 "context" 5 "net" 6 ) 7 8 // SetupContextForConn is a helper function that starts connection I/O interrupter goroutine. 9 func SetupContextForConn(ctx context.Context, conn net.Conn) (done func(*error)) { 10 var ( 11 quit = make(chan struct{}) 12 interrupt = make(chan error, 1) 13 ) 14 go func() { 15 select { 16 case <-quit: 17 interrupt <- nil 18 case <-ctx.Done(): 19 // Close the connection, discarding the error 20 _ = conn.Close() 21 interrupt <- ctx.Err() 22 } 23 }() 24 return func(inputErr *error) { 25 close(quit) 26 if ctxErr := <-interrupt; ctxErr != nil && inputErr != nil { 27 // Return context error to user. 28 inputErr = &ctxErr 29 } 30 } 31 }