gitee.com/liuxuezhan/go-micro-v1.18.0@v1.0.0/util/http/http_test.go (about)

     1  package http
     2  
     3  import (
     4  	"io/ioutil"
     5  	"net"
     6  	"net/http"
     7  	"testing"
     8  
     9  	"gitee.com/liuxuezhan/go-micro-v1.18.0/registry"
    10  	"gitee.com/liuxuezhan/go-micro-v1.18.0/registry/memory"
    11  )
    12  
    13  func TestRoundTripper(t *testing.T) {
    14  	m := memory.NewRegistry()
    15  
    16  	rt := NewRoundTripper(
    17  		WithRegistry(m),
    18  	)
    19  
    20  	http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
    21  		w.Write([]byte(`hello world`))
    22  	})
    23  
    24  	l, err := net.Listen("tcp", "127.0.0.1:0")
    25  	if err != nil {
    26  		t.Fatal(err)
    27  	}
    28  	defer l.Close()
    29  
    30  	go http.Serve(l, nil)
    31  
    32  	m.Register(&registry.Service{
    33  		Name: "example.com",
    34  		Nodes: []*registry.Node{
    35  			{
    36  				Id:      "1",
    37  				Address: l.Addr().String(),
    38  			},
    39  		},
    40  	})
    41  
    42  	req, err := http.NewRequest("GET", "http://example.com", nil)
    43  	if err != nil {
    44  		t.Fatal(err)
    45  	}
    46  
    47  	w, err := rt.RoundTrip(req)
    48  	if err != nil {
    49  		t.Fatal(err)
    50  	}
    51  
    52  	b, err := ioutil.ReadAll(w.Body)
    53  	if err != nil {
    54  		t.Fatal(err)
    55  	}
    56  	w.Body.Close()
    57  
    58  	if string(b) != "hello world" {
    59  		t.Fatal("response is", string(b))
    60  	}
    61  
    62  	// test http request
    63  	c := &http.Client{
    64  		Transport: rt,
    65  	}
    66  
    67  	rsp, err := c.Get("http://example.com")
    68  	if err != nil {
    69  		t.Fatal(err)
    70  	}
    71  
    72  	b, err = ioutil.ReadAll(rsp.Body)
    73  	if err != nil {
    74  		t.Fatal(err)
    75  	}
    76  	rsp.Body.Close()
    77  
    78  	if string(b) != "hello world" {
    79  		t.Fatal("response is", string(b))
    80  	}
    81  
    82  }