Files
zogo/httpprobe/httpprobe_test.go
4566704 caa65209ac feat(httpprobe): go-hua/http 迁入并更名 httpprobe(HTTP/HTTPS 协议探测)
- 原包名 http 与标准库 net/http 严重混淆, 实为按首部字节探测协议,
  更名 httpprobe; spmux 将基于此做单端口分流, 附测试、例程与 README
2026-09-20 12:25:36 +08:00

75 lines
2.0 KiB
Go

package httpprobe
import "testing"
func TestIsHttpMethods(t *testing.T) {
cases := map[string][]byte{
"GET": []byte("GET /index.html HTTP/1.1\r\nHost: a.com\r\n\r\n"),
"POST": []byte("POST /api HTTP/1.1\r\nHost: a.com\r\n\r\n{}"),
"PUT": []byte("PUT /api HTTP/1.1\r\nHost: a.com\r\n\r\n"),
"HEAD": []byte("HEAD / HTTP/1.1\r\nHost: a.com\r\n\r\n"),
"DELETE": []byte("DELETE /api HTTP/1.1\r\nHost: a.com\r\n\r\n"),
"CONNECT": []byte("CONNECT a.com:443 HTTP/1.1\r\n\r\n"),
"OPTIONS": []byte("OPTIONS / HTTP/1.1\r\nHost: a.com\r\n\r\n"),
"TRACE": []byte("TRACE / HTTP/1.1\r\nHost: a.com\r\n\r\n"),
}
for method, data := range cases {
if !IsHttp(data) {
t.Errorf("IsHttp(%s...) 应为 true", method)
}
}
}
func TestIsHttpNegative(t *testing.T) {
if IsHttp([]byte("hello world! This is plain data")) {
t.Error("普通文本不应识别为 HTTP")
}
if IsHttp(nil) {
t.Error("空数据不应识别为 HTTP")
}
if IsHttp([]byte("GET")) {
t.Error("短于 8 字节不应识别为 HTTP")
}
// TLS 握手不是 HTTP
tls := []byte{0x16, 0x03, 0x00, 0x00, 0x01, 0x02, 0x03, 0x04, 0x05}
if IsHttp(tls) {
t.Error("TLS 握手不应识别为 HTTP")
}
}
func TestIsHttpCaseInsensitive(t *testing.T) {
if !IsHttp([]byte("get / HTTP/1.1")) {
t.Error("IsHttp 应大小写不敏感")
}
if !IsHttp([]byte("trace / HTTP/1.1")) {
t.Error("小写 trace 应识别为 HTTP")
}
}
func TestIsHttps(t *testing.T) {
data := make([]byte, 64)
data[0] = 0x16
data[1] = 0x03
data[3] = 0x01
copy(data[40:], "http")
if !IsHttps(data) {
t.Error("TLS ClientHello 应识别为 HTTPS")
}
}
func TestIsHttpsNegative(t *testing.T) {
if IsHttps([]byte("hello world")) {
t.Error("普通文本不应识别为 HTTPS")
}
if IsHttps(nil) {
t.Error("空数据不应识别为 HTTPS")
}
// 非 TLS 握手类型(第一字节不是 0x16)
wrong := make([]byte, 16)
wrong[0] = 0x17
wrong[1] = 0x03
if IsHttps(wrong) {
t.Error("非握手记录不应识别为 HTTPS")
}
}