From 5d6a69806a94c43c4f4532a68f753025822bbdb7 Mon Sep 17 00:00:00 2001 From: HeshamTB Date: Fri, 15 Mar 2024 00:18:41 +0300 Subject: [PATCH] feat: Read stdin for commands to exit Signed-off-by: HeshamTB --- cmd/hvpn-node/hvpn-node.go | 27 +++++++++++++++++++++++---- 1 file changed, 23 insertions(+), 4 deletions(-) diff --git a/cmd/hvpn-node/hvpn-node.go b/cmd/hvpn-node/hvpn-node.go index b7f9293..2663292 100644 --- a/cmd/hvpn-node/hvpn-node.go +++ b/cmd/hvpn-node/hvpn-node.go @@ -1,6 +1,7 @@ package main import ( + "bufio" "fmt" "log/slog" "net" @@ -9,6 +10,7 @@ import ( "net/url" "os" "os/signal" + "strings" "time" "github.com/urfave/cli/v2" @@ -20,7 +22,7 @@ import ( /* Can change all therse vars to local func vars IPPool can be internal to wglink or other abstraction. As well as - POrt, ifname and CIDR and so on. Use Clie.ctx to get the values + Port, ifname and CIDR and so on. Use Clie.ctx to get the values */ var IPPool hvpnnode3.IPPool @@ -271,12 +273,18 @@ func setup() error { wgLink.IPPool = ipPool //defer wgLink.Close() + cInput := make(chan struct{}) + go handleStdin(cInput) c := make(chan os.Signal, 1) signal.Notify(c, os.Interrupt, os.Kill) go func() { - slog.Debug("Listening for SIGINT, SIGKILL") - <- c - slog.Warn("Recived SIGINT! Closing Wireguard Device") + slog.Info("Listening for SIGINT, SIGKILL and user input") + select { + case <- c: + slog.Warn("Recived SIGINT! Closing Wireguard Device") + case <- cInput: + slog.Warn("Recieved quit! Closing Wireguard Device") + } wgLink.Close() os.Exit(0) }() @@ -340,3 +348,14 @@ func testWgPeerAdd(wgLink *hvpnnode3.WGLink) error { return nil } +func handleStdin(c chan struct{}) { + for { + reader := bufio.NewReader(os.Stdin) + slog.Info("Enter 'q' or 'exit' to quit") + in, _ := reader.ReadString('\n') + in = strings.ReplaceAll(in, "\n", "") + if in == "q" || in == "exit" { + c <- struct{}{} + } + } +}