Here is classical example of using defer:
conn, err = amqp.Dial(rabbitMqConnectionString)
if err != nil {
panic(err)
}
defer conn.Close()
In my case the connection is the member of struct and I am using this connnection in the different functions:
type MyServer {
conn *Connection
}
func (s *MyServer) Run() {
s.conn, err = amqp.Dial(rabbitMqConnectionString)
if err != nil {
panic(err)
}
}
func (s *MyServer) DoSomethingWithConnection() {
// ...do something with connection
}
In this case I cannot use defer in the Run() method. But where and how do I need to close connection in this case ?
func (s *MyServer) Stop() {
//Some teardown
s.conn.Close()
}
func main(){
var s *MyServer
...
s.Run()
defer s.Stop()
s.DoSomethingWithConnection()
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With