/
server.go
95 lines (80 loc) · 2.09 KB
/
server.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
package cmd
import (
"context"
"fmt"
"os"
"os/signal"
"syscall"
"github.com/istiofy/istiofy/internal/gateway"
"github.com/istiofy/istiofy/internal/gateway/grpc"
"github.com/istiofy/istiofy/pkg/log"
"github.com/mitchellh/go-homedir"
"github.com/spf13/viper"
"github.com/spf13/cobra"
"github.com/spf13/pflag"
)
var (
// cfgPath is the path to the EnvoyGateway configuration file.
cfgPath string
)
func GetServerCommand() *cobra.Command {
cmd := &cobra.Command{
Use: "server",
Short: "Run both grpc and http server",
RunE: func(cmd *cobra.Command, args []string) error {
log, err := log.New()
if err != nil {
return err
}
cmd.Flags().VisitAll(func(flag *pflag.Flag) {
log.Infof("FLAG: --%s=%q", flag.Name, flag.Value)
})
stop := make(chan struct{})
defer WaitSignal(stop)
if err := grpc.Run(context.Background(), "tcp", ":9090"); err != nil {
log.Fatalf("grpc start error: %s", err)
}
opts := gateway.Options{
Addr: ":8081",
GRPCServer: gateway.Endpoint{
Network: "tcp",
Addr: "localhost:9090",
},
OpenAPIDir: "api/v1",
}
if err := gateway.Run(context.Background(), opts); err != nil {
log.Fatalf("grpc gateway start error: %s", err)
}
return nil
},
}
cobra.OnInitialize(InitConfig)
cmd.PersistentFlags().StringVar(&cfgFile, "config", "./config/config.yaml", "config file (default is $HOME/.istiofy.yaml)")
cmd.Flags().BoolP("toggle", "t", false, "Help message for toggle")
cmd.PersistentFlags().StringVarP(&cfgPath, "config-path", "c", "",
"The path to the configuration file.")
return cmd
}
func WaitSignal(stop chan struct{}) {
sigs := make(chan os.Signal, 1)
signal.Notify(sigs, syscall.SIGINT, syscall.SIGTERM)
<-sigs
close(stop)
}
func InitConfig() {
if cfgFile != "" {
viper.SetConfigFile(cfgFile)
} else {
home, err := homedir.Dir()
if err != nil {
fmt.Println(err)
os.Exit(1)
}
viper.AddConfigPath(home)
viper.SetConfigName(".istiofy")
}
viper.AutomaticEnv()
if err := viper.ReadInConfig(); err == nil {
fmt.Println("Using config file:", viper.ConfigFileUsed())
}
}