2019-06-03 18:44:43 +01:00
|
|
|
package http
|
|
|
|
|
|
|
|
import (
|
|
|
|
"context"
|
|
|
|
"fmt"
|
|
|
|
"net"
|
|
|
|
"net/http"
|
|
|
|
"sync"
|
|
|
|
"testing"
|
|
|
|
|
2020-07-27 13:22:00 +01:00
|
|
|
"github.com/micro/go-micro/v3/client"
|
|
|
|
"github.com/micro/go-micro/v3/registry/memory"
|
|
|
|
"github.com/micro/go-micro/v3/server"
|
|
|
|
"github.com/micro/go-micro/v3/service"
|
|
|
|
"github.com/micro/go-micro/v3/service/mucp"
|
2019-06-03 18:44:43 +01:00
|
|
|
)
|
|
|
|
|
|
|
|
type testHandler struct{}
|
|
|
|
|
|
|
|
func (t *testHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
|
|
|
|
w.Write([]byte(`{"hello": "world"}`))
|
|
|
|
}
|
|
|
|
|
2019-06-07 13:42:39 +01:00
|
|
|
func TestHTTPProxy(t *testing.T) {
|
2019-06-03 18:44:43 +01:00
|
|
|
c, err := net.Listen("tcp", "localhost:0")
|
|
|
|
if err != nil {
|
|
|
|
t.Fatal(err)
|
|
|
|
}
|
|
|
|
defer c.Close()
|
|
|
|
addr := c.Addr().String()
|
|
|
|
|
|
|
|
url := fmt.Sprintf("http://%s", addr)
|
|
|
|
|
|
|
|
testCases := []struct {
|
|
|
|
// http endpoint to call e.g /foo/bar
|
|
|
|
httpEp string
|
|
|
|
// rpc endpoint called e.g Foo.Bar
|
|
|
|
rpcEp string
|
|
|
|
// should be an error
|
|
|
|
err bool
|
|
|
|
}{
|
|
|
|
{"/", "Foo.Bar", false},
|
|
|
|
{"/", "Foo.Baz", false},
|
|
|
|
{"/helloworld", "Hello.World", true},
|
|
|
|
}
|
|
|
|
|
|
|
|
// handler
|
|
|
|
http.Handle("/", new(testHandler))
|
|
|
|
|
|
|
|
// new proxy
|
2019-06-07 13:42:39 +01:00
|
|
|
p := NewSingleHostProxy(url)
|
2019-06-03 18:44:43 +01:00
|
|
|
|
|
|
|
ctx, cancel := context.WithCancel(context.Background())
|
|
|
|
defer cancel()
|
|
|
|
|
|
|
|
var wg sync.WaitGroup
|
|
|
|
wg.Add(1)
|
|
|
|
|
|
|
|
// new micro service
|
2020-07-27 13:22:00 +01:00
|
|
|
service := mucp.NewService(
|
|
|
|
service.Context(ctx),
|
|
|
|
service.Name("foobar"),
|
|
|
|
service.Registry(memory.NewRegistry()),
|
|
|
|
service.AfterStart(func() error {
|
2019-06-03 18:44:43 +01:00
|
|
|
wg.Done()
|
|
|
|
return nil
|
|
|
|
}),
|
|
|
|
)
|
|
|
|
|
|
|
|
// set router
|
|
|
|
service.Server().Init(
|
|
|
|
server.WithRouter(p),
|
|
|
|
)
|
|
|
|
|
|
|
|
// run service
|
|
|
|
// server
|
|
|
|
go http.Serve(c, nil)
|
|
|
|
go service.Run()
|
|
|
|
|
|
|
|
// wait till service is started
|
|
|
|
wg.Wait()
|
|
|
|
|
|
|
|
for _, test := range testCases {
|
|
|
|
req := service.Client().NewRequest("foobar", test.rpcEp, map[string]string{"foo": "bar"}, client.WithContentType("application/json"))
|
|
|
|
var rsp map[string]string
|
|
|
|
err := service.Client().Call(ctx, req, &rsp)
|
|
|
|
if err != nil && test.err == false {
|
|
|
|
t.Fatal(err)
|
|
|
|
}
|
|
|
|
if v := rsp["hello"]; v != "world" {
|
|
|
|
t.Fatalf("Expected hello world got %s from %s", v, test.rpcEp)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|