github.com/ipfans/trojan-go@v0.11.0/tunnel/http/http_test.go (about)

     1  package http
     2  
     3  import (
     4  	"bufio"
     5  	"context"
     6  	"fmt"
     7  	"io/ioutil"
     8  	"net"
     9  	"net/http"
    10  	"testing"
    11  	"time"
    12  
    13  	"github.com/ipfans/trojan-go/common"
    14  	"github.com/ipfans/trojan-go/config"
    15  	"github.com/ipfans/trojan-go/test/util"
    16  	"github.com/ipfans/trojan-go/tunnel/transport"
    17  )
    18  
    19  func TestHTTP(t *testing.T) {
    20  	port := common.PickPort("tcp", "127.0.0.1")
    21  	ctx := config.WithConfig(context.Background(), transport.Name, &transport.Config{
    22  		LocalHost: "127.0.0.1",
    23  		LocalPort: port,
    24  	})
    25  
    26  	tcpServer, err := transport.NewServer(ctx, nil)
    27  	common.Must(err)
    28  	s, err := NewServer(ctx, tcpServer)
    29  	common.Must(err)
    30  
    31  	for i := 0; i < 10; i++ {
    32  		go func() {
    33  			resp, err := http.Get(fmt.Sprintf("http://127.0.0.1:%d", port))
    34  			common.Must(err)
    35  			defer resp.Body.Close()
    36  		}()
    37  		time.Sleep(time.Microsecond * 10)
    38  		conn, err := s.AcceptConn(nil)
    39  		common.Must(err)
    40  		bufReader := bufio.NewReader(bufio.NewReader(conn))
    41  		req, err := http.ReadRequest(bufReader)
    42  		common.Must(err)
    43  		fmt.Println(req)
    44  		ioutil.ReadAll(req.Body)
    45  		req.Body.Close()
    46  		resp, err := http.Get("http://127.0.0.1:" + util.HTTPPort)
    47  		common.Must(err)
    48  		defer resp.Body.Close()
    49  		err = resp.Write(conn)
    50  		common.Must(err)
    51  		buf := [100]byte{}
    52  		_, err = conn.Read(buf[:])
    53  		if err == nil {
    54  			t.Fail()
    55  		}
    56  		conn.Close()
    57  	}
    58  
    59  	req, err := http.NewRequest(http.MethodConnect, "https://google.com:443", nil)
    60  	common.Must(err)
    61  	conn1, err := net.Dial("tcp", fmt.Sprintf("127.0.0.1:%d", port))
    62  	common.Must(err)
    63  	go func() {
    64  		common.Must(req.Write(conn1))
    65  	}()
    66  
    67  	conn2, err := s.AcceptConn(nil)
    68  	common.Must(err)
    69  
    70  	if conn2.Metadata().Port != 443 || conn2.Metadata().DomainName != "google.com" {
    71  		t.Fail()
    72  	}
    73  
    74  	connResp := "HTTP/1.1 200 Connection established\r\n\r\n"
    75  	buf := make([]byte, len(connResp))
    76  	_, err = conn1.Read(buf)
    77  	common.Must(err)
    78  	if string(buf) != connResp {
    79  		t.Fail()
    80  	}
    81  
    82  	if !util.CheckConn(conn1, conn2) {
    83  		t.Fail()
    84  	}
    85  
    86  	conn1.Close()
    87  	conn2.Close()
    88  	s.Close()
    89  }