Skip to content

Commit

Permalink
chore: add SetupContextForConn for common/net
Browse files Browse the repository at this point in the history
  • Loading branch information
wwqgtxx committed Nov 3, 2023
1 parent 885ee7a commit ee3038d
Showing 1 changed file with 31 additions and 0 deletions.
31 changes: 31 additions & 0 deletions common/net/context.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
package net

import (
"context"
"net"
)

// SetupContextForConn is a helper function that starts connection I/O interrupter goroutine.
func SetupContextForConn(ctx context.Context, conn net.Conn) (done func(*error)) {
var (
quit = make(chan struct{})
interrupt = make(chan error, 1)
)
go func() {
select {
case <-quit:
interrupt <- nil
case <-ctx.Done():
// Close the connection, discarding the error
_ = conn.Close()
interrupt <- ctx.Err()
}
}()
return func(inputErr *error) {
close(quit)
if ctxErr := <-interrupt; ctxErr != nil && inputErr != nil {
// Return context error to user.
inputErr = &ctxErr
}
}
}

0 comments on commit ee3038d

Please sign in to comment.