Basic Connection Pool in Go

I started working in Go ~10 months ago, after seeing Rob Pike talk on Concurrency Patterns in Go (link).

Enter my first messing around at a Connection Pool, because I could not find any libs to handle this just yet:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
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
}

//Postgres Pool
var pgPool = &ConnectionPool{}

//function to open postgres connection
func initPostgres() (interface{}, error)  {
  db, err := sql.Open("postgres", "secretstring")
  if err != nil {
    return nil, err
  }
  return db, nil
}