From 0fb0cb92a01a607823302fec306b49d7befceacc Mon Sep 17 00:00:00 2001 From: Brian Picciano Date: Sat, 12 Jan 2019 20:11:22 -0500 Subject: [PATCH] mnet: ListenerOnStart -> MListen, and have it close on mrun.Stop --- mnet/mnet.go | 13 ++++++++++--- mnet/mnet_test.go | 9 +++++---- 2 files changed, 15 insertions(+), 7 deletions(-) diff --git a/mnet/mnet.go b/mnet/mnet.go index 33dbe10..5025c1d 100644 --- a/mnet/mnet.go +++ b/mnet/mnet.go @@ -11,12 +11,13 @@ import ( "github.com/mediocregopher/mediocre-go-lib/mrun" ) -// ListenerOnStart returns a Listener which will be initialized when the start -// event is triggered on ctx (see mrun.Start). +// MListen returns a Listener which will be initialized when the start event is +// triggered on ctx (see mrun.Start), and closed when the stop event is +// triggered on ctx (see mrun.Stop). // // network defaults to "tcp" if empty. defaultAddr defaults to ":0" if empty, // and will be configurable via mcfg. -func ListenerOnStart(ctx mctx.Context, network, defaultAddr string) net.Listener { +func MListen(ctx mctx.Context, network, defaultAddr string) net.Listener { if network == "" { network = "tcp" } @@ -35,6 +36,12 @@ func ListenerOnStart(ctx mctx.Context, network, defaultAddr string) net.Listener return nil }) + // TODO track connections and wait for them to complete before shutting + // down? + mrun.OnStop(ctx, func(mctx.Context) error { + return l.Close() + }) + return &l } diff --git a/mnet/mnet_test.go b/mnet/mnet_test.go index bf878e2..25fcda6 100644 --- a/mnet/mnet_test.go +++ b/mnet/mnet_test.go @@ -37,9 +37,9 @@ func TestIsReservedIP(t *T) { )) } -func TestListen(t *T) { +func TestMListen(t *T) { ctx := mctx.New() - l := ListenerOnStart(ctx, "", "") + l := MListen(ctx, "", "") if err := mcfg.Populate(ctx, nil); err != nil { t.Fatal(err) } else if err := mrun.Start(ctx); err != nil { @@ -65,6 +65,7 @@ func TestListen(t *T) { t.Fatalf("read %q from conn", b) } - conn.Close() - l.Close() + if err := mrun.Stop(ctx); err != nil { + t.Fatal(err) + } }