http_test.go 2.1 KB

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