feat(conn): 自 go-hua 迁入限速统计连接装饰器

- net.Conn 透明叠加 rate 限速与 flow 流量统计
- 内部依赖改指 zogo/flow 与 zogo/rate, 附测试、例程与 README
This commit is contained in:
2026-09-20 12:25:35 +08:00
parent f9f7c7c92f
commit a81e467a31
4 changed files with 326 additions and 0 deletions
+61
View File
@@ -0,0 +1,61 @@
// conn 包示例:带流量统计/限速的连接包装(读写自动计入 flow/rate,Close 幂等)
package main
import (
"fmt"
"io"
"net"
"sync"
"git.zeroonesoft.cn/golib/zogo/conn"
"git.zeroonesoft.cn/golib/zogo/flow"
"git.zeroonesoft.cn/golib/zogo/rate"
)
func main() {
// 本地 echo 服务
l, err := net.Listen("tcp", "127.0.0.1:0")
if err != nil {
panic(err)
}
go func() {
for {
c, err := l.Accept()
if err != nil {
return
}
go func() {
io.Copy(c, c)
c.Close()
}()
}
}()
raw, err := net.Dial("tcp", l.Addr().String())
if err != nil {
panic(err)
}
// rate.NewRate(0) 表示不限速;限速时传入 Mbps 并调用 Start()
r := rate.NewRate(0)
f := &flow.Flow{}
wg := &sync.WaitGroup{}
wg.Add(1)
// 用 conn.Conn 包装原始连接
c := conn.NewConn(raw, r, f, wg)
c.Write([]byte("hello go-hua"))
buf := make([]byte, 12)
n, _ := c.Read(buf)
fmt.Println("echo:", string(buf[:n]))
// 读写流量自动统计
send, recv := f.Get()
fmt.Printf("连接累计流量: 写入 %d 字节, 读取 %d 字节\n", send, recv)
// Close 只会真正关闭一次,并触发 wg.Done
c.Close()
wg.Wait()
fmt.Println("连接已关闭")
}