2020-08-25 13:44:41 +03:00
|
|
|
// +build ignore
|
|
|
|
|
2019-05-31 01:52:10 +03:00
|
|
|
package http
|
|
|
|
|
|
|
|
import (
|
|
|
|
"io/ioutil"
|
|
|
|
"net"
|
|
|
|
"net/http"
|
|
|
|
"testing"
|
|
|
|
|
2021-01-29 13:17:32 +03:00
|
|
|
"github.com/unistack-org/micro/v3/register"
|
|
|
|
"github.com/unistack-org/micro/v3/register/memory"
|
2020-08-19 17:47:17 +03:00
|
|
|
"github.com/unistack-org/micro/v3/router"
|
2021-01-29 13:17:32 +03:00
|
|
|
regRouter "github.com/unistack-org/micro/v3/router/register"
|
2019-05-31 01:52:10 +03:00
|
|
|
)
|
|
|
|
|
|
|
|
func TestRoundTripper(t *testing.T) {
|
2021-01-29 13:17:32 +03:00
|
|
|
m := memory.NewRegister()
|
|
|
|
r := regRouter.NewRouter(router.Register(m))
|
2019-05-31 01:52:10 +03:00
|
|
|
|
2020-07-01 19:06:59 +03:00
|
|
|
rt := NewRoundTripper(WithRouter(r))
|
2019-05-31 01:52:10 +03:00
|
|
|
|
|
|
|
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
|
|
|
|
w.Write([]byte(`hello world`))
|
|
|
|
})
|
|
|
|
|
|
|
|
l, err := net.Listen("tcp", "127.0.0.1:0")
|
|
|
|
if err != nil {
|
|
|
|
t.Fatal(err)
|
|
|
|
}
|
|
|
|
defer l.Close()
|
|
|
|
|
|
|
|
go http.Serve(l, nil)
|
|
|
|
|
2021-01-29 13:17:32 +03:00
|
|
|
m.Register(®ister.Service{
|
2019-05-31 01:52:10 +03:00
|
|
|
Name: "example.com",
|
2021-01-29 13:17:32 +03:00
|
|
|
Nodes: []*register.Node{
|
2019-05-31 01:52:10 +03:00
|
|
|
{
|
|
|
|
Id: "1",
|
2019-07-08 10:01:42 +03:00
|
|
|
Address: l.Addr().String(),
|
2019-05-31 01:52:10 +03:00
|
|
|
},
|
|
|
|
},
|
|
|
|
})
|
|
|
|
|
|
|
|
req, err := http.NewRequest("GET", "http://example.com", nil)
|
|
|
|
if err != nil {
|
|
|
|
t.Fatal(err)
|
|
|
|
}
|
|
|
|
|
|
|
|
w, err := rt.RoundTrip(req)
|
|
|
|
if err != nil {
|
|
|
|
t.Fatal(err)
|
|
|
|
}
|
|
|
|
|
|
|
|
b, err := ioutil.ReadAll(w.Body)
|
|
|
|
if err != nil {
|
|
|
|
t.Fatal(err)
|
|
|
|
}
|
|
|
|
w.Body.Close()
|
|
|
|
|
|
|
|
if string(b) != "hello world" {
|
|
|
|
t.Fatal("response is", string(b))
|
|
|
|
}
|
|
|
|
|
|
|
|
// test http request
|
|
|
|
c := &http.Client{
|
|
|
|
Transport: rt,
|
|
|
|
}
|
|
|
|
|
|
|
|
rsp, err := c.Get("http://example.com")
|
|
|
|
if err != nil {
|
|
|
|
t.Fatal(err)
|
|
|
|
}
|
|
|
|
|
|
|
|
b, err = ioutil.ReadAll(rsp.Body)
|
|
|
|
if err != nil {
|
|
|
|
t.Fatal(err)
|
|
|
|
}
|
|
|
|
rsp.Body.Close()
|
|
|
|
|
|
|
|
if string(b) != "hello world" {
|
|
|
|
t.Fatal("response is", string(b))
|
|
|
|
}
|
|
|
|
|
|
|
|
}
|