Created
July 25, 2015 00:49
-
-
Save donpark/9631812a44d8581916ce to your computer and use it in GitHub Desktop.
Abstract lazy connection with optional auto disconnect on idle timeout
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package lazy | |
import ( | |
"sync" | |
"time" | |
) | |
type Connection struct { | |
sync.Mutex | |
conn interface{} | |
expires time.Time | |
Connect func() interface{} | |
Disconnect func(conn interface{}) | |
IdleTimeout time.Duration | |
} | |
func (c *Connection) Get() interface{} { | |
c.Lock() | |
defer c.Unlock() | |
if c.conn != nil { | |
return c.conn | |
} | |
c.conn = c.Connect() | |
if c.conn != nil && c.IdleTimeout > 0 { | |
c.KeepAlive() | |
go c.idle() | |
} | |
return c.conn | |
} | |
func (c *Connection) Close() { | |
c.Lock() | |
defer c.Unlock() | |
if c.conn == nil { | |
return | |
} | |
if c.Disconnect != nil { | |
c.Disconnect(c.conn) | |
} | |
c.conn = nil | |
} | |
func (c *Connection) KeepAlive() { | |
c.expires = time.Now().Add(c.IdleTimeout) | |
} | |
func (c *Connection) idle() { | |
for { | |
til := time.Since(c.expires) | |
if til > 0 { | |
time.Sleep(til) | |
} | |
if time.Since(c.expires) > 0 { | |
c.Close() | |
break | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment