feat: Read stdin for commands to exit

Signed-off-by: HeshamTB <hishaminv@gmail.com>
This commit is contained in:
HeshamTB 2024-03-15 00:18:41 +03:00
parent 0c703465af
commit 5d6a69806a
Signed by: Hesham
GPG Key ID: 74876157D199B09E

View File

@ -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{}{}
}
}
}