Files
4566704 a81e467a31 feat(conn): 自 go-hua 迁入限速统计连接装饰器
- net.Conn 透明叠加 rate 限速与 flow 流量统计
- 内部依赖改指 zogo/flow 与 zogo/rate, 附测试、例程与 README
2026-09-20 12:25:35 +08:00

42 lines
991 B
Markdown
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
# conn
`net.Conn` 装饰器:在读写路径上透明叠加带宽限速(rate)与流量统计(flow),
可选关联 `sync.WaitGroup` 管理连接生命周期。
> 迁移自 go-hua/conn,内部依赖指向本仓库 flow/rate。
## 用法
```go
import (
"net"
"sync"
"git.zeroonesoft.cn/golib/zogo/conn"
"git.zeroonesoft.cn/golib/zogo/flow"
"git.zeroonesoft.cn/golib/zogo/rate"
)
var wg sync.WaitGroup
wg.Add(1)
f := &flow.Flow{}
r := rate.NewRate(1024 * 512) // 512 KB/s,0 表示不限速
r.Start()
c := conn.NewConn(rawConn, r, f, &wg)
defer c.Close()
// 之后像普通 net.Conn 一样使用:Read/Write 已自动限速并累计流量
c.Write(buf)
n, _ := c.Read(buf)
send, recv := f.Get() // 读写流量统计
```
完整可运行例程:[examples/conn/main.go](../examples/conn/main.go)
## 注意
- `rate` 传 nil 表示不限速;`flow` 传 nil 表示不统计。
- `Close` 幂等,并会 `wg.Done()`(前提是创建时传入了 wg)。