refactor: do cli.Exit in top level

Signed-off-by: HeshamTB <hishaminv@gmail.com>
This commit is contained in:
HeshamTB 2024-03-18 01:43:07 +03:00
parent e5e4641264
commit 4c6e251247
Signed by: Hesham
GPG Key ID: 74876157D199B09E

View File

@ -2,6 +2,7 @@ package main
import (
"bufio"
"errors"
"fmt"
"log/slog"
"net/http"
@ -158,7 +159,7 @@ func createCliApp() *cli.App {
Action: func(ctx *cli.Context, s string) error {
_, err := netip.ParseAddr(s)
if err != nil {
return cli.Exit(fmt.Sprintf("Can not parse %s as a network IP", s), 1)
return errors.New(fmt.Sprintf("Can not parse %s as a network IP", s))
}
return nil
},
@ -177,7 +178,7 @@ func createCliApp() *cli.App {
app.Action = func(ctx *cli.Context) error {
err := setup(ctx)
if err != nil {
return err
return cli.Exit(err, 1)
}
run(ctx)
return nil
@ -206,7 +207,7 @@ func setup(ctx *cli.Context) error {
slog.Info("Creating a private key")
privateKey, err = wgtypes.GeneratePrivateKey()
if err != nil {
return cli.Exit(err, 1)
return err
}
slog.Debug(fmt.Sprintf("new public key: %s", privateKey.PublicKey().String()))
return nil
@ -231,7 +232,7 @@ func setup(ctx *cli.Context) error {
privateKeyStr := make([]byte, 45)
n, err := privKeyFile.Read(privateKeyStr)
if err != nil {
return cli.Exit(err, 1)
return err
}
if n != 45 {
slog.Warn("Private key length did not math the expected 45!")
@ -241,7 +242,7 @@ func setup(ctx *cli.Context) error {
privateKey, err = wgtypes.ParseKey(string(privateKeyStr))
slog.Debug("Keyfile opened for reading")
if err != nil {
return cli.Exit(err, 1)
return err
}
slog.Debug("Private key parsed and is correct")
}
@ -256,7 +257,7 @@ func setup(ctx *cli.Context) error {
if err != nil {
slog.Warn("Error while initlizing Wireguard netlink and device!")
slog.Warn("Ensure to run as root or with CAP_NET_ADMIN")
return cli.Exit(err, 1)
return err
}
wgLink = wg
@ -266,7 +267,7 @@ func setup(ctx *cli.Context) error {
dev, err := wgLink.Device(InterfaceName)
if err != nil {
return cli.Exit(err, 1)
return err
}
slog.Info("Initialized Wireguard device using wgctrl")
@ -294,7 +295,7 @@ func setup(ctx *cli.Context) error {
err = ipPool.Free(testVip)
if err != nil {
slog.Error("Could not free test Vip from IPPool!", err)
return cli.Exit(err.Error(), 1)
return err
}
slog.Debug("Test IP Freed")
@ -343,10 +344,12 @@ func testWgPeerAdd(wgLink *hvpnnode3.WGLink) error {
if err != nil {
return err
}
peers, err := wgLink.GetAllPeers()
if len(peers) != 0 {
slog.Warn(fmt.Sprintf("Expected 0 peers, got %d", len(peers)))
}
slog.Debug("Removed test peer")
return nil