gitee.com/liuxuezhan/go-micro-v1.18.0@v1.0.0/api/handler/http/http_test.go (about) 1 package http 2 3 import ( 4 "net" 5 "net/http" 6 "net/http/httptest" 7 "testing" 8 9 "gitee.com/liuxuezhan/go-micro-v1.18.0/api/handler" 10 "gitee.com/liuxuezhan/go-micro-v1.18.0/api/router" 11 regRouter "gitee.com/liuxuezhan/go-micro-v1.18.0/api/router/registry" 12 "gitee.com/liuxuezhan/go-micro-v1.18.0/config/cmd" 13 "gitee.com/liuxuezhan/go-micro-v1.18.0/registry" 14 "gitee.com/liuxuezhan/go-micro-v1.18.0/registry/memory" 15 ) 16 17 func testHttp(t *testing.T, path, service, ns string) { 18 r := memory.NewRegistry() 19 cmd.DefaultCmd = cmd.NewCmd(cmd.Registry(&r)) 20 21 l, err := net.Listen("tcp", "127.0.0.1:0") 22 if err != nil { 23 t.Fatal(err) 24 } 25 defer l.Close() 26 27 s := ®istry.Service{ 28 Name: service, 29 Nodes: []*registry.Node{ 30 { 31 Id: service + "-1", 32 Address: l.Addr().String(), 33 }, 34 }, 35 } 36 37 r.Register(s) 38 defer r.Deregister(s) 39 40 // setup the test handler 41 m := http.NewServeMux() 42 m.HandleFunc(path, func(w http.ResponseWriter, r *http.Request) { 43 w.Write([]byte(`you got served`)) 44 }) 45 46 // start http test serve 47 go http.Serve(l, m) 48 49 // create new request and writer 50 w := httptest.NewRecorder() 51 req, err := http.NewRequest("POST", path, nil) 52 if err != nil { 53 t.Fatal(err) 54 } 55 56 // initialise the handler 57 rt := regRouter.NewRouter( 58 router.WithHandler("http"), 59 router.WithNamespace(ns), 60 ) 61 62 p := NewHandler(handler.WithRouter(rt)) 63 64 // execute the handler 65 p.ServeHTTP(w, req) 66 67 if w.Code != 200 { 68 t.Fatalf("Expected 200 response got %d %s", w.Code, w.Body.String()) 69 } 70 71 if w.Body.String() != "you got served" { 72 t.Fatalf("Expected body: you got served. Got: %s", w.Body.String()) 73 } 74 } 75 76 func TestHttpHandler(t *testing.T) { 77 testData := []struct { 78 path string 79 service string 80 namespace string 81 }{ 82 { 83 "/test/foo", 84 "go.micro.api.test", 85 "go.micro.api", 86 }, 87 { 88 "/test/foo/baz", 89 "go.micro.api.test", 90 "go.micro.api", 91 }, 92 { 93 "/v1/foo", 94 "go.micro.api.v1.foo", 95 "go.micro.api", 96 }, 97 { 98 "/v1/foo/bar", 99 "go.micro.api.v1.foo", 100 "go.micro.api", 101 }, 102 { 103 "/v2/baz", 104 "go.micro.api.v2.baz", 105 "go.micro.api", 106 }, 107 { 108 "/v2/baz/bar", 109 "go.micro.api.v2.baz", 110 "go.micro.api", 111 }, 112 { 113 "/v2/baz/bar", 114 "v2.baz", 115 "", 116 }, 117 } 118 119 for _, d := range testData { 120 testHttp(t, d.path, d.service, d.namespace) 121 } 122 }