From 709ca7f23b6c00753c1ed95f805a8a79ef3e592f Mon Sep 17 00:00:00 2001 From: Sebastian Frank Date: Thu, 10 Feb 2022 14:59:39 +0100 Subject: [PATCH] close finalizer --- mgo.go | 37 +++++++++++++++++++++++++++++++++---- 1 file changed, 33 insertions(+), 4 deletions(-) diff --git a/mgo.go b/mgo.go index 7a4d703..53f9cd6 100644 --- a/mgo.go +++ b/mgo.go @@ -2,37 +2,66 @@ package mgocrud import ( "errors" + "fmt" + "runtime" mgo "gopkg.in/mgo.v2" ) type MgoConnection struct { connection *mgo.Session + closed bool } func NewMgoConnection(dial string) (Connection, error) { + fmt.Println("CONNECTION CREATE") connection, err := mgo.Dial(dial) if err != nil { return nil, err } connection.SetMode(mgo.Monotonic, true) - return &MgoConnection{connection: connection}, nil + c := &MgoConnection{connection: connection} + runtime.SetFinalizer(c, func(c *MgoConnection) { + fmt.Println("CONNECTION CLOSE FINALIZER") + if !c.closed { + c.Close() + } + }) + return c, nil } func (c *MgoConnection) Close() { - c.connection.Close() + fmt.Println("CONNECTION CLOSE MANUALLY") + if !c.closed { + c.connection.Close() + c.closed = true + } + runtime.SetFinalizer(c, nil) } type MgoSession struct { session *mgo.Session + closed bool } func (s *MgoSession) Close() { - s.session.Close() + fmt.Println("SESSION CLOSE MANUALLY") + if !s.closed { + s.session.Close() + s.closed = true + } + runtime.SetFinalizer(s, nil) } func (c *MgoConnection) NewSession() Session { - return &MgoSession{session: c.connection.Copy()} + fmt.Println("SESSION CREATE") + s := &MgoSession{session: c.connection.Copy()} + runtime.SetFinalizer(s, func(s *MgoSession) { + fmt.Println("SESSION CLOSE FINALIZER") + if !s.closed { + s.Close() + } + }) } type MgoDatabase struct {