mnet: ListenerOnStart -> MListen, and have it close on mrun.Stop

This commit is contained in:
Brian Picciano 2019-01-12 20:11:22 -05:00
parent 0ef6997f40
commit 0fb0cb92a0
2 changed files with 15 additions and 7 deletions

View File

@ -11,12 +11,13 @@ import (
"github.com/mediocregopher/mediocre-go-lib/mrun" "github.com/mediocregopher/mediocre-go-lib/mrun"
) )
// ListenerOnStart returns a Listener which will be initialized when the start // MListen returns a Listener which will be initialized when the start event is
// event is triggered on ctx (see mrun.Start). // 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, // network defaults to "tcp" if empty. defaultAddr defaults to ":0" if empty,
// and will be configurable via mcfg. // 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 == "" { if network == "" {
network = "tcp" network = "tcp"
} }
@ -35,6 +36,12 @@ func ListenerOnStart(ctx mctx.Context, network, defaultAddr string) net.Listener
return nil 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 return &l
} }

View File

@ -37,9 +37,9 @@ func TestIsReservedIP(t *T) {
)) ))
} }
func TestListen(t *T) { func TestMListen(t *T) {
ctx := mctx.New() ctx := mctx.New()
l := ListenerOnStart(ctx, "", "") l := MListen(ctx, "", "")
if err := mcfg.Populate(ctx, nil); err != nil { if err := mcfg.Populate(ctx, nil); err != nil {
t.Fatal(err) t.Fatal(err)
} else if err := mrun.Start(ctx); err != nil { } else if err := mrun.Start(ctx); err != nil {
@ -65,6 +65,7 @@ func TestListen(t *T) {
t.Fatalf("read %q from conn", b) t.Fatalf("read %q from conn", b)
} }
conn.Close() if err := mrun.Stop(ctx); err != nil {
l.Close() t.Fatal(err)
}
} }