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 package main
import ( import (
"bufio"
"fmt" "fmt"
"log/slog" "log/slog"
"net" "net"
@ -9,6 +10,7 @@ import (
"net/url" "net/url"
"os" "os"
"os/signal" "os/signal"
"strings"
"time" "time"
"github.com/urfave/cli/v2" "github.com/urfave/cli/v2"
@ -20,7 +22,7 @@ import (
/* /*
Can change all therse vars to local func vars Can change all therse vars to local func vars
IPPool can be internal to wglink or other abstraction. As well as 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 var IPPool hvpnnode3.IPPool
@ -271,12 +273,18 @@ func setup() error {
wgLink.IPPool = ipPool wgLink.IPPool = ipPool
//defer wgLink.Close() //defer wgLink.Close()
cInput := make(chan struct{})
go handleStdin(cInput)
c := make(chan os.Signal, 1) c := make(chan os.Signal, 1)
signal.Notify(c, os.Interrupt, os.Kill) signal.Notify(c, os.Interrupt, os.Kill)
go func() { go func() {
slog.Debug("Listening for SIGINT, SIGKILL") slog.Info("Listening for SIGINT, SIGKILL and user input")
<- c select {
slog.Warn("Recived SIGINT! Closing Wireguard Device") case <- c:
slog.Warn("Recived SIGINT! Closing Wireguard Device")
case <- cInput:
slog.Warn("Recieved quit! Closing Wireguard Device")
}
wgLink.Close() wgLink.Close()
os.Exit(0) os.Exit(0)
}() }()
@ -340,3 +348,14 @@ func testWgPeerAdd(wgLink *hvpnnode3.WGLink) error {
return nil 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{}{}
}
}
}