From 531ccfb14c0c3442a20f15fe53dd36c4e60636a0 Mon Sep 17 00:00:00 2001 From: Wojtek Mach Date: Tue, 26 Mar 2024 23:20:55 +0100 Subject: [PATCH] cmd/listen: Exit when stdin is closed (#1155) Co-authored-by: Ian Jabour <58703040+ianjabour-stripe@users.noreply.github.com> --- pkg/cmd/listen.go | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) diff --git a/pkg/cmd/listen.go b/pkg/cmd/listen.go index 2bcf7861d..1a8aa1d4d 100644 --- a/pkg/cmd/listen.go +++ b/pkg/cmd/listen.go @@ -1,6 +1,7 @@ package cmd import ( + "bufio" "context" "fmt" "net/url" @@ -130,6 +131,8 @@ func (lc *listenCmd) runListenCmd(cmd *cobra.Command, args []string) error { }).Debug("Ctrl+C received, cleaning up...") }) + ctx = withStdinCloseCancel(ctx) + client := &stripe.Client{ APIKey: key, BaseURL: apiBase, @@ -198,6 +201,20 @@ func withSIGTERMCancel(ctx context.Context, onCancel func()) context.Context { return ctx } +func withStdinCloseCancel(ctx context.Context) context.Context { + ctx, cancel := context.WithCancel(ctx) + + go func() { + scanner := bufio.NewScanner(os.Stdin) + for scanner.Scan() { + } + if scanner.Err() == nil { + cancel() + } + }() + return ctx +} + func createVisitor(logger *log.Logger, format string, printJSON bool) *websocket.Visitor { var s *spinner.Spinner