Add synchronization to connection pool
This commit is contained in:
parent
85f8530fd3
commit
594bb2ec19
12
conn_pool.go
12
conn_pool.go
|
@ -4,6 +4,7 @@ import (
|
||||||
"crypto/rand"
|
"crypto/rand"
|
||||||
"encoding/base64"
|
"encoding/base64"
|
||||||
"errors"
|
"errors"
|
||||||
|
"sync"
|
||||||
|
|
||||||
imapclient "github.com/emersion/go-imap/client"
|
imapclient "github.com/emersion/go-imap/client"
|
||||||
)
|
)
|
||||||
|
@ -21,7 +22,7 @@ var ErrSessionExpired = errors.New("session expired")
|
||||||
|
|
||||||
// TODO: expiration timer
|
// TODO: expiration timer
|
||||||
type ConnPool struct {
|
type ConnPool struct {
|
||||||
// TODO: add synchronization
|
locker sync.Mutex
|
||||||
conns map[string]*imapclient.Client
|
conns map[string]*imapclient.Client
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -32,6 +33,9 @@ func NewConnPool() *ConnPool {
|
||||||
}
|
}
|
||||||
|
|
||||||
func (pool *ConnPool) Get(token string) (*imapclient.Client, error) {
|
func (pool *ConnPool) Get(token string) (*imapclient.Client, error) {
|
||||||
|
pool.locker.Lock()
|
||||||
|
defer pool.locker.Unlock()
|
||||||
|
|
||||||
conn, ok := pool.conns[token]
|
conn, ok := pool.conns[token]
|
||||||
if !ok {
|
if !ok {
|
||||||
return nil, ErrSessionExpired
|
return nil, ErrSessionExpired
|
||||||
|
@ -40,6 +44,9 @@ func (pool *ConnPool) Get(token string) (*imapclient.Client, error) {
|
||||||
}
|
}
|
||||||
|
|
||||||
func (pool *ConnPool) Put(conn *imapclient.Client) (token string, err error) {
|
func (pool *ConnPool) Put(conn *imapclient.Client) (token string, err error) {
|
||||||
|
pool.locker.Lock()
|
||||||
|
defer pool.locker.Unlock()
|
||||||
|
|
||||||
for {
|
for {
|
||||||
var err error
|
var err error
|
||||||
token, err = generateToken()
|
token, err = generateToken()
|
||||||
|
@ -57,7 +64,10 @@ func (pool *ConnPool) Put(conn *imapclient.Client) (token string, err error) {
|
||||||
|
|
||||||
go func() {
|
go func() {
|
||||||
<-conn.LoggedOut()
|
<-conn.LoggedOut()
|
||||||
|
|
||||||
|
pool.locker.Lock()
|
||||||
delete(pool.conns, token)
|
delete(pool.conns, token)
|
||||||
|
pool.locker.Unlock()
|
||||||
}()
|
}()
|
||||||
|
|
||||||
return token, nil
|
return token, nil
|
||||||
|
|
Loading…
Reference in a new issue