23b58ddd23
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).
79 lines
1.6 KiB
Go
79 lines
1.6 KiB
Go
package http
|
|
|
|
import (
|
|
"bufio"
|
|
"context"
|
|
"net"
|
|
"net/http"
|
|
"testing"
|
|
|
|
"github.com/go-gost/core/handler"
|
|
xrecorder "github.com/go-gost/x/recorder"
|
|
)
|
|
|
|
func TestHandleUDP_Disabled_WritesForbidden(t *testing.T) {
|
|
h := &httpHandler{
|
|
options: handler.Options{
|
|
Logger: &testLogger{},
|
|
},
|
|
}
|
|
h.md.proxyAgent = defaultProxyAgent
|
|
h.md.enableUDP = false
|
|
|
|
client, server := net.Pipe()
|
|
defer client.Close()
|
|
defer server.Close()
|
|
|
|
ro := &xrecorder.HandlerRecorderObject{}
|
|
|
|
go func() {
|
|
h.handleUDP(context.Background(), server, "", ro, &testLogger{})
|
|
}()
|
|
|
|
br := bufio.NewReader(client)
|
|
resp, err := http.ReadResponse(br, nil)
|
|
if err != nil {
|
|
t.Fatalf("read response: %v", err)
|
|
}
|
|
defer resp.Body.Close()
|
|
|
|
if resp.StatusCode != http.StatusForbidden {
|
|
t.Errorf("got status %d, want %d", resp.StatusCode, http.StatusForbidden)
|
|
}
|
|
}
|
|
|
|
func TestHandleUDP_Enabled_NilRouter(t *testing.T) {
|
|
h := &httpHandler{
|
|
options: handler.Options{
|
|
Logger: &testLogger{},
|
|
},
|
|
}
|
|
h.md.proxyAgent = defaultProxyAgent
|
|
h.md.enableUDP = true
|
|
|
|
client, server := net.Pipe()
|
|
defer client.Close()
|
|
defer server.Close()
|
|
|
|
ro := &xrecorder.HandlerRecorderObject{}
|
|
|
|
go func() {
|
|
// OK response sent, then nil router causes error
|
|
err := h.handleUDP(context.Background(), server, "", ro, &testLogger{})
|
|
if err == nil {
|
|
t.Log("expected error with nil router for UDP")
|
|
}
|
|
}()
|
|
|
|
br := bufio.NewReader(client)
|
|
resp, err := http.ReadResponse(br, nil)
|
|
if err != nil {
|
|
t.Fatalf("read response: %v", err)
|
|
}
|
|
defer resp.Body.Close()
|
|
|
|
if resp.StatusCode != http.StatusOK {
|
|
t.Errorf("got status %d, want %d", resp.StatusCode, http.StatusOK)
|
|
}
|
|
}
|