move conn acquire release to wrapper func accepting callback
This commit is contained in:
@@ -6,6 +6,8 @@ import (
|
||||
"encoding/base64"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"hash/crc32"
|
||||
"io"
|
||||
"log"
|
||||
"net"
|
||||
"os"
|
||||
@@ -102,3 +104,27 @@ func (c Config) Close() {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (c Config) WithConn(hashKey string, foo func(net.Conn) error) error {
|
||||
hash := int(crc32.ChecksumIEEE([]byte(hashKey)))
|
||||
hashIdx := hash % len(c.forwards)
|
||||
forward := c.forwards[hashIdx]
|
||||
|
||||
log.Printf("acquire conn %v", hashIdx)
|
||||
forwardCon := forward.Get()
|
||||
if forwardCon == nil {
|
||||
log.Printf("got a nil conn to %v", hashIdx)
|
||||
return io.EOF
|
||||
}
|
||||
forwardConn := forwardCon.(net.Conn)
|
||||
|
||||
if err := foo(forwardConn); err != nil {
|
||||
log.Printf("errored with conn %v: %v", hashIdx, err)
|
||||
forwardConn.Close()
|
||||
return err
|
||||
}
|
||||
|
||||
log.Printf("release conn %v", hashIdx)
|
||||
forward.Put(forwardConn)
|
||||
return nil
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user