Follow

Talking shop, #golang question 

() folks:

I have a library with a func that takes a context, and reads from a net.Conn. A user was confused that the function would block on reading the Conn even after the context was expired. I said they can call `conn.SetDeadline`, but they asked that I also have the context cancel it. Is it normal to have the context cancel the conn.Read, or should I keep a separate deadline and require that the user set both?

Talking shop, #golang question 

@sam not sure of the exact details, but this post here may help: ieftimov.com/post/make-resilie Usually, the code holding the control over the connection (I.e your function) will check on context cancellation and will cancel the connection as a result.

Talking shop, #golang question 

@preslavrachev Thanks; I ended up realizing that I should have shared the original library. The function in question takes in a `net.Conn`, but there are also two convenience methods that dial one for you (NewSession/DialSession). The one that takes in a Conn I decided it was up to the user to set timeouts on everything separately for maximum flexibility, but for DialSession it's a bug if no timeout at all is set on the conn, so I made that one respect the context.

Talking shop, #golang question 

@preslavrachev Good article; thanks for the link. Unfortunately this is more about TCP timeouts and it doesn't mention those or this problem much. The basic question is: if the user creates a conn with a deadline and a context with a deadline and passes them both into a function: do they expect both deadlines to be respected, or the context deadline to apply to reads from the conn as well as everything else?

Talking shop, #golang question 

@sam is there a possibility to abstract the creation of a connection? This way, a function called NewConnection will only take a context instance. This same function will set up a goroutine that continuously checks for context deadlines or can cancellations. If one happens, it will cancel the connection too. Again, that’s just a speculation in my head.

Talking shop, #golang question 

@preslavrachev Sort of. There are the helper versions which dial the conn I mentioned, these definitely have to manage its timeouts. There is also a net.Dialer wrapper that looks up SRV records and the like, but I think that context should be for the dial itself, not for the resulting connection per convention (eg. net.Dial and the like). We'll see, I may just manage the conn everywhere to reduce the number of differences between the functions.

Sign in to participate in the conversation
social.coop

The social network of the future: No ads, no corporate surveillance, ethical design, and decentralization! Own your data with Mastodon!