github.com/xtls/xray-core@v1.8.12-0.20240518155711-3168d27b0bdb/transport/internet/http/http_test.go (about) 1 package http_test 2 3 import ( 4 "context" 5 "crypto/rand" 6 "testing" 7 "time" 8 9 "github.com/google/go-cmp/cmp" 10 "github.com/xtls/xray-core/common" 11 "github.com/xtls/xray-core/common/buf" 12 "github.com/xtls/xray-core/common/net" 13 "github.com/xtls/xray-core/common/protocol/tls/cert" 14 "github.com/xtls/xray-core/testing/servers/tcp" 15 "github.com/xtls/xray-core/transport/internet" 16 . "github.com/xtls/xray-core/transport/internet/http" 17 "github.com/xtls/xray-core/transport/internet/stat" 18 "github.com/xtls/xray-core/transport/internet/tls" 19 ) 20 21 func TestHTTPConnection(t *testing.T) { 22 port := tcp.PickPort() 23 24 listener, err := Listen(context.Background(), net.LocalHostIP, port, &internet.MemoryStreamConfig{ 25 ProtocolName: "http", 26 ProtocolSettings: &Config{}, 27 SecurityType: "tls", 28 SecuritySettings: &tls.Config{ 29 Certificate: []*tls.Certificate{tls.ParseCertificate(cert.MustGenerate(nil, cert.CommonName("www.example.com")))}, 30 }, 31 }, func(conn stat.Connection) { 32 go func() { 33 defer conn.Close() 34 35 b := buf.New() 36 defer b.Release() 37 38 for { 39 if _, err := b.ReadFrom(conn); err != nil { 40 return 41 } 42 _, err := conn.Write(b.Bytes()) 43 common.Must(err) 44 } 45 }() 46 }) 47 common.Must(err) 48 49 defer listener.Close() 50 51 time.Sleep(time.Second) 52 53 dctx := context.Background() 54 conn, err := Dial(dctx, net.TCPDestination(net.LocalHostIP, port), &internet.MemoryStreamConfig{ 55 ProtocolName: "http", 56 ProtocolSettings: &Config{}, 57 SecurityType: "tls", 58 SecuritySettings: &tls.Config{ 59 ServerName: "www.example.com", 60 AllowInsecure: true, 61 }, 62 }) 63 common.Must(err) 64 defer conn.Close() 65 66 const N = 1024 67 b1 := make([]byte, N) 68 common.Must2(rand.Read(b1)) 69 b2 := buf.New() 70 71 nBytes, err := conn.Write(b1) 72 common.Must(err) 73 if nBytes != N { 74 t.Error("write: ", nBytes) 75 } 76 77 b2.Clear() 78 common.Must2(b2.ReadFullFrom(conn, N)) 79 if r := cmp.Diff(b2.Bytes(), b1); r != "" { 80 t.Error(r) 81 } 82 83 nBytes, err = conn.Write(b1) 84 common.Must(err) 85 if nBytes != N { 86 t.Error("write: ", nBytes) 87 } 88 89 b2.Clear() 90 common.Must2(b2.ReadFullFrom(conn, N)) 91 if r := cmp.Diff(b2.Bytes(), b1); r != "" { 92 t.Error(r) 93 } 94 }