优化项目机构和服务端协程控制逻辑

This commit is contained in:
2025-02-25 14:48:50 +08:00
parent 83fd749d50
commit 7f23e2741f
21 changed files with 732 additions and 440 deletions

View File

@@ -1,8 +1,13 @@
package utils
import (
"context"
"io"
"log/slog"
"net"
"sync"
"github.com/pkg/errors"
)
func ReadByte(reader io.Reader) (byte, error) {
@@ -31,3 +36,42 @@ func Close[T io.Closer](v T) {
slog.Warn("对象关闭失败", "err", err)
}
}
func ConnChan(ctx context.Context, ls net.Listener) chan net.Conn {
connCh := make(chan net.Conn)
go func() {
for {
conn, err := ls.Accept()
if err != nil {
slog.Error("接受连接失败", err)
// 临时错误重试连接
var ne net.Error
if errors.As(err, &ne) && ne.Temporary() {
slog.Debug("临时错误重试")
continue
}
return
}
// ctx 取消后退出
select {
case <-ctx.Done():
Close(conn)
return
case connCh <- conn:
}
}
}()
return connCh
}
func WaitChan(ctx context.Context, wg *sync.WaitGroup) chan struct{} {
ch := make(chan struct{})
go func() {
wg.Wait()
select {
case <-ctx.Done():
case ch <- struct{}{}:
}
}()
return ch
}