Skip to content

Commit 1f48c60

Browse files
authored
refactor: enhance context management by adding drain func and unified channel initialization
1 parent 8c93ce2 commit 1f48c60

File tree

3 files changed

+23
-15
lines changed

3 files changed

+23
-15
lines changed

internal/client.go

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -30,6 +30,7 @@ func NewClient(parsedURL *url.URL, logger *logs.Logger) *Client {
3030
logger: logger,
3131
semaphore: make(chan struct{}, semaphoreLimit),
3232
signalChan: make(chan string, semaphoreLimit),
33+
errChan: make(chan error, 3),
3334
},
3435
tunnelName: parsedURL.Hostname(),
3536
}
@@ -73,8 +74,8 @@ func (c *Client) Run() {
7374

7475
// start 启动客户端服务
7576
func (c *Client) start() error {
76-
// 初始化基本信息
77-
c.initBackground()
77+
// 初始化上下文
78+
c.initContext()
7879

7980
// 通过是否监听成功判断单端转发或双端握手
8081
if err := c.initTunnelListener(); err == nil {

internal/common.go

Lines changed: 17 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -167,13 +167,12 @@ func (c *Common) getAddress(parsedURL *url.URL) {
167167
}
168168
}
169169

170-
// initBackground 初始化基本信息
171-
func (c *Common) initBackground() {
170+
// initContext 初始化上下文
171+
func (c *Common) initContext() {
172172
if c.cancel != nil {
173173
c.cancel()
174174
}
175175
c.ctx, c.cancel = context.WithCancel(context.Background())
176-
c.errChan = make(chan error, 3)
177176
}
178177

179178
// initTargetListener 初始化目标监听器
@@ -226,6 +225,17 @@ func (c *Common) initTunnelListener() error {
226225
return nil
227226
}
228227

228+
// drain 清空通道中的所有元素
229+
func drain[T any](ch <-chan T) {
230+
for {
231+
select {
232+
case <-ch:
233+
default:
234+
return
235+
}
236+
}
237+
}
238+
229239
// stop 共用停止服务
230240
func (c *Common) stop() {
231241
// 取消上下文
@@ -285,14 +295,10 @@ func (c *Common) stop() {
285295
c.logger.Debug("Tunnel listener closed: %v", c.tunnelListener.Addr())
286296
}
287297

288-
// 清空信号通道
289-
for {
290-
select {
291-
case <-c.signalChan:
292-
default:
293-
return
294-
}
295-
}
298+
// 清空通道
299+
drain(c.semaphore)
300+
drain(c.signalChan)
301+
drain(c.errChan)
296302
}
297303

298304
// shutdown 共用优雅关闭

internal/server.go

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -34,6 +34,7 @@ func NewServer(parsedURL *url.URL, tlsCode string, tlsConfig *tls.Config, logger
3434
logger: logger,
3535
semaphore: make(chan struct{}, semaphoreLimit),
3636
signalChan: make(chan string, semaphoreLimit),
37+
errChan: make(chan error, 3),
3738
},
3839
tlsConfig: tlsConfig,
3940
}
@@ -77,8 +78,8 @@ func (s *Server) Run() {
7778

7879
// start 启动服务端
7980
func (s *Server) start() error {
80-
// 初始化基本信息
81-
s.initBackground()
81+
// 初始化上下文
82+
s.initContext()
8283

8384
// 初始化隧道监听器
8485
if err := s.initTunnelListener(); err != nil {

0 commit comments

Comments
 (0)