Indeed, servers are easier, and if all you're looking to do is to issue a cancellation signal which immediately closes every active connection, the code you posted is perfectly adequate.
I don't expect calling SetDeadline to ever cause a panic, regardless of the state of the connection. On Wed, Jul 8, 2020 at 1:43 PM Brian Candler <b.cand...@pobox.com> wrote: > On Wednesday, 8 July 2020 11:17:56 UTC+1, Andrei Tudor Călin wrote: >> >> I think this works for some cases, but it is potentially wasteful (and >> even leaky) in terms of resource usage. >> >> For example, if ctx is context.Background(), it leaks a goroutine for >> every connection >> > > If this is a network server, that's easily fixed: you make a new ctx for > each connection (derived from the main one), and cancel it just before the > connection is closed. I think it's useful anyway to have a context which > covers the lifetime of that connection. > > > It also keeps the additional goroutine around for the entire lifetime > of the connection. > > Goroutines are cheap. > > How about the following? > > type Deadliner interface { > SetDeadline(t time.Time) error > } > > func addContext(ctx context.Context, d Deadliner) { > go func() { > <-ctx.Done() > d.SetDeadline(time.Now()) > }() > } > > func handleConnection(ctx context.Context, conn net.Conn) { > ctx, cancel := context.WithCancel(ctx) > defer cancel() > addContext(ctx, conn) > > ... rest of code goes here > } > > That seems pretty clean to me. My only concern is there's a possibility > of calling SetDeadline on an already-closed connection, and whether that > would cause a panic. > >> -- > You received this message because you are subscribed to the Google Groups > "golang-nuts" group. > To unsubscribe from this group and stop receiving emails from it, send an > email to golang-nuts+unsubscr...@googlegroups.com. > To view this discussion on the web visit > https://groups.google.com/d/msgid/golang-nuts/aa0eaf7a-27a8-4dc0-a6d7-245317cc4187o%40googlegroups.com > <https://groups.google.com/d/msgid/golang-nuts/aa0eaf7a-27a8-4dc0-a6d7-245317cc4187o%40googlegroups.com?utm_medium=email&utm_source=footer> > . > -- Andrei Călin -- You received this message because you are subscribed to the Google Groups "golang-nuts" group. To unsubscribe from this group and stop receiving emails from it, send an email to golang-nuts+unsubscr...@googlegroups.com. To view this discussion on the web visit https://groups.google.com/d/msgid/golang-nuts/CANnvmN7Lk0qO2L-D1e9nj0zK9LZjs2mjbR8cFLcVEHkU_otoMw%40mail.gmail.com.