Files
x/handler/http/websocket_test.go
T
ginuerzh 3246b39c93 refactor(handler/http): split handler monolith into 7 focused files with 96 unit tests
Extract the 1024-line handler.go into concern-focused files:
  util.go       — 5 pure functions (decodeServerName, basicProxyAuth, upgradeType,
                  normalizeHostPort, buildConnectResponse) — 100% coverage
  auth.go       — authenticate (5 probe-resistance strategies + knock) + checkRateLimit
  connect.go    — handleConnect, sniffAndHandle, dial, setupTrafficLimiter
  proxy.go      — handleProxy keep-alive loop, proxyRoundTrip, handleUpgradeResponse
  websocket.go  — WebSocket frame sniffing/recording with rate-limited sampling
  udp.go        — UDP-over-HTTP relay with SOCKS5 tunnel
  metadata.go   — metadata struct, parseMetadata, probeResistance type

Key improvements:
- Transport injection (http.RoundTripper field) enables testing without real network
- Nil Router guards in dial, handleUDP, and nil Addr guard in checkRateLimit
- Pure functions converted from methods to package-level (no state dependency)
- setupTrafficLimiter returns cleanup closure to preserve defer lifetime
- handleConnect accepts caller's resp for correct recorder status capture
- Comprehensive package doc with full request-flow documentation

96 tests: 100% on pure functions, 86% on metadata parsing, 55% overall (integration
paths verified by e2e tests).
2026-05-28 23:06:37 +08:00

51 lines
1.1 KiB
Go

package http
import (
"bytes"
"context"
"io"
"testing"
"github.com/go-gost/core/handler"
"github.com/go-gost/core/recorder"
)
func TestCopyWebsocketFrame_ReadError(t *testing.T) {
h := &httpHandler{
options: handler.Options{
Logger: &testLogger{},
},
}
buf := &bytes.Buffer{}
err := h.copyWebsocketFrame(io.Discard, bytes.NewReader(nil), buf, "client", nil)
if err == nil {
t.Error("expected read error from empty reader")
}
}
func TestCopyWebsocketDirection_ErrorReader(t *testing.T) {
h := &httpHandler{
options: handler.Options{
Logger: &testLogger{},
},
}
h.recorder = recorder.RecorderObject{}
errc := make(chan error, 1)
go h.copyWebsocketDirection(context.Background(), &errorReader{}, io.Discard, "client", nil, 10.0, &testLogger{}, errc)
err := <-errc
if err == nil {
t.Error("expected error from error reader")
}
}
// errorReader always returns an error.
type errorReader struct{}
func (r *errorReader) Read(p []byte) (int, error) { return 0, io.ErrUnexpectedEOF }
func (r *errorReader) Write(p []byte) (int, error) { return len(p), nil }
func (r *errorReader) Close() error { return nil }