1 Star 0 Fork 0

青文杰/mongo-go-driver

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
克隆/下载
connection_test.go 1.97 KB
一键复制 编辑 原始数据 按行查看 历史
Kris Brandow 提交于 2018-11-16 17:28 . Restructure repository
// Copyright (C) MongoDB, Inc. 2017-present.
//
// Licensed under the Apache License, Version 2.0 (the "License"); you may
// not use this file except in compliance with the License. You may obtain
// a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
package connection
import (
"context"
"net"
"sync"
"testing"
)
// bootstrapConnection creates a listener that will listen for a single connection
// on the return address. The user provided run function will be called with the accepted
// connection. The user is responsible for closing the connection.
func bootstrapConnections(t *testing.T, num int, run func(net.Conn)) net.Addr {
l, err := net.Listen("tcp", "localhost:0")
if err != nil {
t.Errorf("Could not set up a listener: %v", err)
t.FailNow()
}
go func() {
for i := 0; i < num; i++ {
c, err := l.Accept()
if err != nil {
t.Errorf("Could not accept a connection: %v", err)
}
go run(c)
}
_ = l.Close()
}()
return l.Addr()
}
type netconn struct {
net.Conn
closed chan struct{}
d *dialer
}
func (nc *netconn) Close() error {
nc.closed <- struct{}{}
nc.d.connclosed(nc)
return nc.Conn.Close()
}
type dialer struct {
Dialer
opened map[*netconn]struct{}
closed map[*netconn]struct{}
sync.Mutex
}
func newdialer(d Dialer) *dialer {
return &dialer{Dialer: d, opened: make(map[*netconn]struct{}), closed: make(map[*netconn]struct{})}
}
func (d *dialer) DialContext(ctx context.Context, network, address string) (net.Conn, error) {
d.Lock()
defer d.Unlock()
c, err := d.Dialer.DialContext(ctx, network, address)
if err != nil {
return nil, err
}
nc := &netconn{Conn: c, closed: make(chan struct{}, 1), d: d}
d.opened[nc] = struct{}{}
return nc, nil
}
func (d *dialer) connclosed(nc *netconn) {
d.Lock()
defer d.Unlock()
d.closed[nc] = struct{}{}
}
func (d *dialer) lenopened() int {
d.Lock()
defer d.Unlock()
return len(d.opened)
}
func (d *dialer) lenclosed() int {
d.Lock()
defer d.Unlock()
return len(d.closed)
}
Loading...
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
1
https://gitee.com/qingwenjie/mongo-go-driver.git
git@gitee.com:qingwenjie/mongo-go-driver.git
qingwenjie
mongo-go-driver
mongo-go-driver
v0.3.0

搜索帮助