2019-05-31 00:52:10 +02:00
|
|
|
package http
|
|
|
|
|
|
|
|
import (
|
2021-10-30 20:24:40 +02:00
|
|
|
"io"
|
2019-05-31 00:52:10 +02:00
|
|
|
"net"
|
|
|
|
"net/http"
|
|
|
|
"testing"
|
|
|
|
|
2024-06-04 22:40:43 +02:00
|
|
|
"go-micro.dev/v5/registry"
|
2019-05-31 00:52:10 +02:00
|
|
|
)
|
|
|
|
|
|
|
|
func TestRoundTripper(t *testing.T) {
|
2020-12-29 17:49:26 +02:00
|
|
|
m := registry.NewMemoryRegistry()
|
2019-05-31 00:52:10 +02:00
|
|
|
|
|
|
|
rt := NewRoundTripper(
|
|
|
|
WithRegistry(m),
|
|
|
|
)
|
|
|
|
|
|
|
|
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)
|
|
|
|
|
|
|
|
m.Register(®istry.Service{
|
|
|
|
Name: "example.com",
|
|
|
|
Nodes: []*registry.Node{
|
|
|
|
{
|
|
|
|
Id: "1",
|
2019-07-08 09:01:42 +02:00
|
|
|
Address: l.Addr().String(),
|
2019-05-31 00:52:10 +02: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)
|
|
|
|
}
|
|
|
|
|
2021-10-30 20:24:40 +02:00
|
|
|
b, err := io.ReadAll(w.Body)
|
2019-05-31 00:52:10 +02:00
|
|
|
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)
|
|
|
|
}
|
|
|
|
|
2021-10-30 20:24:40 +02:00
|
|
|
b, err = io.ReadAll(rsp.Body)
|
2019-05-31 00:52:10 +02:00
|
|
|
if err != nil {
|
|
|
|
t.Fatal(err)
|
|
|
|
}
|
|
|
|
rsp.Body.Close()
|
|
|
|
|
|
|
|
if string(b) != "hello world" {
|
|
|
|
t.Fatal("response is", string(b))
|
|
|
|
}
|
|
|
|
}
|