How to prevent resource leaks in Go (based on given TCP connection example)? [closed]

3 weeks ago 35
ARTICLE AD BOX

I've been playing with a very simple TCP server in golang (net.Listener + net.Conn). Within my code I open a TCP connection and pass it to a goroutine to read data from it. In that goroutine, I think, I should have called the traditional defer connection.Close(). But I forgot to do it and there was no error produced. I'm afraid that something like that might happen again and it will create leaks in my system that I will not notice.

I'm used to programming in C++ and in there I would have used a scoped guard to Close() the connection automatically when exiting scope. What is the best practice way to handle such situations in Go and is there any way to guarantee that something important like that will not be missed? And why doesn't Go say anything about it? Is such resource management completely my responsibility?

P.S. I'm following a course on learning the HTTP protocol and it did not offer any solution nor tests to guarantee not missing the problem.

Read Entire Article