refactor(handler/http): extract Authenticator, SnifferBuilder, and normalizeRequest as testable units

Extract three pure-logic components from httpHandler to eliminate I/O
coupling from auth and sniffing construction, enabling synchronous unit
tests and reducing per-request allocation in sniffAndHandle:

- Authenticator struct with AuthResult return type — auth decisions no
  longer write to the connection; callers handle response I/O. Auth
  tests drop net.Pipe/goroutines for direct return-value assertions.
- SnifferBuilder pre-built in Init and reused per-connection via Build(),
  replacing inline sniffing.Sniffer{} construction in sniffAndHandle.
- normalizeRequest extracted to util.go with NormalizedRequest type,
  collapsing 20 lines of inline URL/normalisation into a single call.
- knockMatch extracted as standalone pure function.
- clampBodySize exported as ClampBodySize for cross-package use.
- util_test.go with 22 tests covering utility functions.
- helpers_test.go consolidates shared test fakes (logger, observer, conn).
This commit is contained in:
ginuerzh
2026-05-29 00:14:44 +08:00
parent c246a1d4fa
commit 23b58ddd23
18 changed files with 685 additions and 524 deletions
+48
View File
@@ -9,6 +9,7 @@ import (
"net/http"
"strings"
"github.com/asaskevich/govalidator"
"golang.org/x/net/http/httpguts"
)
@@ -84,3 +85,50 @@ func buildConnectResponse(proxyAgent string) []byte {
return []byte("HTTP/1.1 200 Connection established\r\n" +
"Proxy-Agent: " + proxyAgent + "\r\n\r\n")
}
// NormalizedRequest holds the parsed target address and network from an
// HTTP proxy request after URL inference, GOST v2 compatibility decoding,
// and host normalisation.
type NormalizedRequest struct {
Network string // "tcp" or "udp"
Addr string // host:port (default port appended when absent)
}
// normalizeRequest extracts the target address and network from an HTTP
// request. It infers the URL scheme when absent, decodes GOST v2
// compatibility headers (Gost-Target, X-Gost-Target), detects the
// transport protocol from X-Gost-Protocol, and normalises the host to
// include a port.
//
// The function mutates req.URL.Scheme and req.Host as side effects so
// that the caller's request reflects the inferred target.
func normalizeRequest(req *http.Request) *NormalizedRequest {
if !req.URL.IsAbs() {
host := req.Host
if h, _, err := net.SplitHostPort(host); err == nil {
host = h
}
if govalidator.IsDNSName(host) || net.ParseIP(host) != nil {
req.URL.Scheme = "http"
}
}
network := req.Header.Get("X-Gost-Protocol")
if network != "udp" {
network = "tcp"
}
if v := req.Header.Get("Gost-Target"); v != "" {
if h, err := decodeServerName(v); err == nil {
req.Host = h
}
}
if v := req.Header.Get("X-Gost-Target"); v != "" {
if h, err := decodeServerName(v); err == nil {
req.Host = h
}
}
addr := normalizeHostPort(req.Host, "80")
return &NormalizedRequest{Network: network, Addr: addr}
}