Quick note on runtime.Goexit() and deferred close of nats connection

315 views
Skip to first unread message

Anthony Eden

unread,
Sep 7, 2015, 2:24:54 AM9/7/15
to nats
I spent some time setting up a test environment with nats and I ran into an issue with the use of defer with runtime.Goexit(). The example code in https://github.com/nats-io/nats/blob/master/examples/nats-sub.go does not use defer to close the connection, but the code examples in https://github.com/nats-io/nats/blob/master/README.md do, so if you are naive like me and put the two together, the connection on the subscriber end is always closed by the defer when runtime.Goexit() is called.

Anyhow, I just wanted to call this out so in case someone else runs into the same issue they are aware of what's going on. Here is the documentation for runtime.Goexit():


One simple fix might be to remove the deferred connection close from the README documentation to avoid confusion.

Sincerely,
Anthony Eden

Derek Collison

unread,
Sep 7, 2015, 8:31:11 PM9/7/15
to nats
Thank, yes you are right that if you use defers and Goexit that they will be triggered and the connection will be closed. The trick I am using here is to avoid exiting the main loop with an exit code without requiring an endless for loop etc at the end of main for the utility apps. This as far as I know is fairly common practice.

Agree that it could be confusing with the example codes using defers.
Reply all
Reply to author
Forward
0 new messages