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

     1  package http
     2  
     3  import (
     4  	"context"
     5  	"fmt"
     6  	"net"
     7  	"net/http"
     8  	"sync"
     9  	"testing"
    10  
    11  	"gitee.com/liuxuezhan/go-micro-v1.18.0"
    12  	"gitee.com/liuxuezhan/go-micro-v1.18.0/client"
    13  	"gitee.com/liuxuezhan/go-micro-v1.18.0/registry/memory"
    14  	"gitee.com/liuxuezhan/go-micro-v1.18.0/server"
    15  )
    16  
    17  type testHandler struct{}
    18  
    19  func (t *testHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
    20  	w.Write([]byte(`{"hello": "world"}`))
    21  }
    22  
    23  func TestHTTPProxy(t *testing.T) {
    24  	c, err := net.Listen("tcp", "localhost:0")
    25  	if err != nil {
    26  		t.Fatal(err)
    27  	}
    28  	defer c.Close()
    29  	addr := c.Addr().String()
    30  
    31  	url := fmt.Sprintf("http://%s", addr)
    32  
    33  	testCases := []struct {
    34  		// http endpoint to call e.g /foo/bar
    35  		httpEp string
    36  		// rpc endpoint called e.g Foo.Bar
    37  		rpcEp string
    38  		// should be an error
    39  		err bool
    40  	}{
    41  		{"/", "Foo.Bar", false},
    42  		{"/", "Foo.Baz", false},
    43  		{"/helloworld", "Hello.World", true},
    44  	}
    45  
    46  	// handler
    47  	http.Handle("/", new(testHandler))
    48  
    49  	// new proxy
    50  	p := NewSingleHostProxy(url)
    51  
    52  	ctx, cancel := context.WithCancel(context.Background())
    53  	defer cancel()
    54  
    55  	var wg sync.WaitGroup
    56  	wg.Add(1)
    57  
    58  	// new micro service
    59  	service := micro.NewService(
    60  		micro.Context(ctx),
    61  		micro.Name("foobar"),
    62  		micro.Registry(memory.NewRegistry()),
    63  		micro.AfterStart(func() error {
    64  			wg.Done()
    65  			return nil
    66  		}),
    67  	)
    68  
    69  	// set router
    70  	service.Server().Init(
    71  		server.WithRouter(p),
    72  	)
    73  
    74  	// run service
    75  	// server
    76  	go http.Serve(c, nil)
    77  	go service.Run()
    78  
    79  	// wait till service is started
    80  	wg.Wait()
    81  
    82  	for _, test := range testCases {
    83  		req := service.Client().NewRequest("foobar", test.rpcEp, map[string]string{"foo": "bar"}, client.WithContentType("application/json"))
    84  		var rsp map[string]string
    85  		err := service.Client().Call(ctx, req, &rsp)
    86  		if err != nil && test.err == false {
    87  			t.Fatal(err)
    88  		}
    89  		if v := rsp["hello"]; v != "world" {
    90  			t.Fatalf("Expected hello world got %s from %s", v, test.rpcEp)
    91  		}
    92  	}
    93  }