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