Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When and how to close resources if they are members of the struct

Tags:

go

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 ?

like image 255
ceth Avatar asked Nov 30 '25 01:11

ceth


1 Answers

func (s *MyServer) Stop() {
    //Some teardown
   s.conn.Close()
}
func main(){
    var s *MyServer
    ...
    s.Run()
    defer s.Stop()
    s.DoSomethingWithConnection()
}
like image 67
Uvelichitel Avatar answered Dec 02 '25 16:12

Uvelichitel



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!