Created
June 30, 2013 00:50
-
-
Save alexblom/6f06caf7e6166e5f14d2 to your computer and use it in GitHub Desktop.
This file contains 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
type MemberInitFunction func() (interface{}, error) | |
type ConnectionPool struct { | |
size int | |
conn chan interface{} | |
} | |
func (p *ConnectionPool) Init(size int, initFn MemberInitFunction) error { | |
p.conn = make(chan interface{}, size) | |
for i := 0; i < size; i++ { | |
conn, err := initFn() | |
if err != nil { | |
return err | |
} | |
// If the init function succeeded, add the connection to the channel | |
p.conn <- conn | |
} | |
p.size = size | |
return nil | |
} | |
//Get connection, block if none available | |
//Any call to get should defer.Release | |
func (p *ConnectionPool) Get() interface{} { | |
return <-p.conn | |
} | |
//Release connection back to pool | |
func (p *ConnectionPool) Release(conn interface{}) { | |
p.conn <- conn | |
} | |
//accessible Postgres Pool | |
var pgPool = &ConnectionPool{} | |
//function to open postgres connection | |
//services as a MemberInitFunction in pgPool | |
func initPostgres() (interface{}, error) { | |
db, err := sql.Open("postgres", "secretstring") | |
if err != nil { | |
return nil, err | |
} | |
return db, nil | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment