2020-10-30 23:27:33 +03:00
|
|
|
package http_test
|
|
|
|
|
|
|
|
import (
|
2020-11-03 02:24:07 +03:00
|
|
|
"context"
|
2020-10-30 23:27:33 +03:00
|
|
|
"fmt"
|
|
|
|
"io/ioutil"
|
|
|
|
"net/http"
|
|
|
|
"testing"
|
|
|
|
|
2021-01-16 02:49:58 +03:00
|
|
|
memory "github.com/unistack-org/micro-registry-memory/v3"
|
|
|
|
httpsrv "github.com/unistack-org/micro-server-http/v3"
|
2020-10-30 23:27:33 +03:00
|
|
|
"github.com/unistack-org/micro/v3/server"
|
|
|
|
)
|
|
|
|
|
|
|
|
func TestHTTPServer(t *testing.T) {
|
|
|
|
reg := memory.NewRegistry()
|
2020-11-03 02:24:07 +03:00
|
|
|
ctx := context.Background()
|
2020-10-30 23:27:33 +03:00
|
|
|
|
|
|
|
// create server
|
|
|
|
srv := httpsrv.NewServer(server.Registry(reg))
|
|
|
|
|
|
|
|
// create server mux
|
|
|
|
mux := http.NewServeMux()
|
|
|
|
mux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
|
|
|
|
w.Write([]byte(`hello world`))
|
|
|
|
})
|
|
|
|
|
|
|
|
// create handler
|
|
|
|
hd := srv.NewHandler(mux)
|
|
|
|
|
|
|
|
// register handler
|
|
|
|
if err := srv.Handle(hd); err != nil {
|
|
|
|
t.Fatal(err)
|
|
|
|
}
|
|
|
|
|
|
|
|
// start server
|
|
|
|
if err := srv.Start(); err != nil {
|
|
|
|
t.Fatal(err)
|
|
|
|
}
|
|
|
|
|
|
|
|
// lookup server
|
2020-11-03 02:24:07 +03:00
|
|
|
service, err := reg.GetService(ctx, server.DefaultName)
|
2020-10-30 23:27:33 +03:00
|
|
|
if err != nil {
|
|
|
|
t.Fatal(err)
|
|
|
|
}
|
|
|
|
|
|
|
|
if len(service) != 1 {
|
|
|
|
t.Fatalf("Expected 1 service got %d: %+v", len(service), service)
|
|
|
|
}
|
|
|
|
|
|
|
|
if len(service[0].Nodes) != 1 {
|
|
|
|
t.Fatalf("Expected 1 node got %d: %+v", len(service[0].Nodes), service[0].Nodes)
|
|
|
|
}
|
|
|
|
|
|
|
|
// make request
|
|
|
|
rsp, err := http.Get(fmt.Sprintf("http://%s", service[0].Nodes[0].Address))
|
|
|
|
if err != nil {
|
|
|
|
t.Fatal(err)
|
|
|
|
}
|
|
|
|
defer rsp.Body.Close()
|
|
|
|
|
|
|
|
b, err := ioutil.ReadAll(rsp.Body)
|
|
|
|
if err != nil {
|
|
|
|
t.Fatal(err)
|
|
|
|
}
|
|
|
|
|
|
|
|
if s := string(b); s != "hello world" {
|
|
|
|
t.Fatalf("Expected response %s, got %s", "hello world", s)
|
|
|
|
}
|
|
|
|
|
|
|
|
// stop server
|
|
|
|
if err := srv.Stop(); err != nil {
|
|
|
|
t.Fatal(err)
|
|
|
|
}
|
|
|
|
}
|