Refactor proxyConnection
gosunuts committed
Feb 26, 2026 at 11:19 UTC
6b2489732b17bce17fdf2f09ac27dd5e3684385f
1 file changed
+12
-9
cmd/portal-tunnel/main.go
+12
-9
@@ -177,7 +177,7 @@ func runServiceTunnel(ctx context.Context, relayURLs []string, cfg Config, origi
177
if cfg.TLSEnable {
178
proxyType = "TLS→TCP"
179
}
180
- if err := proxyConnection(ctx, cfg.Host, relayConn); err != nil {
180
+ if err := proxyConnection(ctx, cfg.Host, relayConn, cfg.TLSEnable); err != nil {
181
log.Error().Str("service", cfg.Name).Str("proxy", proxyType).Err(err).Msg("Proxy error")
182
}
183
log.Info().Str("service", cfg.Name).Str("proxy", proxyType).Msg("Connection closed")
@@ -226,7 +226,7 @@ var bufferPool = sync.Pool{
226
227
// proxyConnection proxies data between relay and local service using raw TCP.
228
// It ensures complete data transfer before closing connections.
229
-func proxyConnection(ctx context.Context, localAddr string, relayConn net.Conn) error {
229
+func proxyConnection(ctx context.Context, localAddr string, relayConn net.Conn, tlsEnabled bool) error {
230
defer relayConn.Close()
231
232
// Try to connect to local service (no retry)
@@ -236,7 +236,10 @@ func proxyConnection(ctx context.Context, localAddr string, relayConn net.Conn)
236
log.Debug().
237
Str("local_addr", localAddr).
238
Err(err).
239
- Msg("Local service unavailable, returning service unavailable page")
239
+ Msg("Local service unavailable")
240
+ if tlsEnabled {
241
+ return fmt.Errorf("local service unavailable: %w", err)
242
+ }
243
return writeEmptyHTTPResponse(relayConn)
244
}
245
defer localConn.Close()
@@ -259,9 +262,9 @@ func proxyConnection(ctx context.Context, localAddr string, relayConn net.Conn)
262
263
// Relay -> Local
264
go func() {
262
- buf := *bufferPool.Get().(*[]byte)
263
- defer bufferPool.Put(&buf)
264
- _, err := io.CopyBuffer(localConn, relayConn, buf)
265
+ bufPtr := bufferPool.Get().(*[]byte)
266
+ defer bufferPool.Put(bufPtr)
267
+ _, err := io.CopyBuffer(localConn, relayConn, *bufPtr)
268
if err != nil {
269
log.Debug().Err(err).Msg("relay->local copy ended")
270
}
@@ -274,9 +277,9 @@ func proxyConnection(ctx context.Context, localAddr string, relayConn net.Conn)
277
278
// Local -> Relay
279
go func() {
277
- buf := *bufferPool.Get().(*[]byte)
278
- defer bufferPool.Put(&buf)
279
- _, err := io.CopyBuffer(relayConn, localConn, buf)
280
+ bufPtr := bufferPool.Get().(*[]byte)
281
+ defer bufferPool.Put(bufPtr)
282
+ _, err := io.CopyBuffer(relayConn, localConn, *bufPtr)
283
if err != nil {
284
log.Debug().Err(err).Msg("local->relay copy ended")
285
}