-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
127 lines (103 loc) · 2.44 KB
/
main.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
package main
import (
"context"
"errors"
"fmt"
"log"
"os"
"os/signal"
"path"
"strings"
"syscall"
"github.com/mitchellh/go-homedir"
"github.com/spf13/cobra"
"github.com/spf13/viper"
)
var (
cfgFile string
cfgName string
)
var (
version = "v0.0.0"
commit = "dev"
)
func main() {
cobra.OnInitialize(initCobra)
rootCmd := &cobra.Command{
Use: "netboard",
Short: "Simple and secure network clipboard sharing engine",
SilenceUsage: true,
SilenceErrors: true,
TraverseChildren: true,
PersistentPreRunE: func(cmd *cobra.Command, args []string) error {
if err := viper.BindPFlags(cmd.PersistentFlags()); err != nil {
return err
}
return viper.BindPFlags(cmd.Flags())
},
Run: func(cmd *cobra.Command, args []string) {
if viper.GetBool("version") {
fmt.Printf("netboard %s (%s)\n", version, commit)
os.Exit(0)
}
},
}
rootCmd.Flags().Bool("version", false, "Show version")
rootCmd.AddCommand(
serverCmd,
listenCmd,
)
mainCtx, cancelFunc := context.WithCancel(context.Background())
defer cancelFunc()
signalCh := make(chan os.Signal, 1)
signal.Reset(syscall.SIGINT, syscall.SIGTERM)
signal.Notify(signalCh, syscall.SIGINT, syscall.SIGTERM)
go func() {
<-signalCh
cancelFunc()
signal.Stop(signalCh)
close(signalCh)
}()
if err := rootCmd.ExecuteContext(mainCtx); err != nil {
fmt.Fprintln(os.Stderr, err.Error())
os.Exit(1)
}
}
func initCobra() {
viper.SetEnvPrefix("netboard")
viper.AutomaticEnv()
viper.SetEnvKeyReplacer(strings.NewReplacer("-", "_"))
home, err := homedir.Dir()
if err != nil {
log.Fatalln("unable to find home dir: ", err)
}
if cfgFile == "" {
cfgFile = os.Getenv("NETBOARD_CONFIG")
}
if cfgFile != "" {
if _, err := os.Stat(cfgFile); os.IsNotExist(err) {
log.Fatalln("config file does not exist", err)
}
viper.SetConfigType("yaml")
viper.SetConfigFile(cfgFile)
if err = viper.ReadInConfig(); err != nil {
log.Fatalln("unable to read config", cfgFile)
}
return
}
viper.AddConfigPath(path.Join(home, ".config", "netboard"))
viper.AddConfigPath("/usr/local/etc/netboard")
viper.AddConfigPath("/etc/netboard")
if cfgName == "" {
cfgName = os.Getenv("NETBOARD_CONFIG_NAME")
}
if cfgName == "" {
cfgName = "config"
}
viper.SetConfigName(cfgName)
if err = viper.ReadInConfig(); err != nil {
if !errors.As(err, &viper.ConfigFileNotFoundError{}) {
log.Fatalln("unable to read config:", err)
}
}
}