From ee601a7b5f8e5f2127f591f931ca370f54c4029e Mon Sep 17 00:00:00 2001 From: Dmitrii Stepanov Date: Mon, 30 Oct 2023 12:34:02 +0300 Subject: [PATCH] [#3] dialer: Add default dialer. Signed-off-by: Dmitrii Stepanov --- default.go | 31 +++++++++++++++++++++++++++++++ default_test.go | 29 +++++++++++++++++++++++++++++ 2 files changed, 60 insertions(+) create mode 100644 default.go create mode 100644 default_test.go diff --git a/default.go b/default.go new file mode 100644 index 0000000..7776a78 --- /dev/null +++ b/default.go @@ -0,0 +1,31 @@ +package multinet + +import ( + "context" + "fmt" + "net" +) + +var ( + defaultDialer Multidialer + defaultDialerErr error +) + +func init() { + var err error + defaultDialer, err = NewDialer(Config{ + Balancer: BalancerTypeRoundRobin, + Subnets: []string{"0.0.0.0/0", "::/0"}, + }) + if err != nil { + defaultDialerErr = fmt.Errorf("failed to initialize default dialier: %w", err) + } +} + +// Dial dials provided network and address using default dialer. +func Dial(network, address string) (net.Conn, error) { + if defaultDialerErr != nil { + return nil, defaultDialerErr + } + return defaultDialer.DialContext(context.Background(), network, address) +} diff --git a/default_test.go b/default_test.go new file mode 100644 index 0000000..b5616d1 --- /dev/null +++ b/default_test.go @@ -0,0 +1,29 @@ +//go:build integration + +package multinet + +import ( + "fmt" + "net/http" + "testing" + + "github.com/stretchr/testify/require" +) + +func TestDefaultDialer(t *testing.T) { + srv := startHTTP(t) + defer require.NoError(t, srv.Close()) + + conn, err := Dial("tcp", "localhost:8080") + require.NoError(t, err) + require.NoError(t, conn.Close()) +} + +func startHTTP(t *testing.T) *http.Server { + srv := &http.Server{Addr: ":8080"} + http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) { fmt.Fprintf(w, "Test stub") }) + go func() { + require.ErrorIs(t, srv.ListenAndServe(), http.ErrServerClosed) + }() + return srv +}