viper-app/cmd/svr.go

86 lines
1.7 KiB
Go
Raw Normal View History

2023-02-03 16:18:31 +08:00
package cmd
import (
"context"
"demo-server/internal/model"
"demo-server/internal/server"
2023-02-03 16:18:31 +08:00
"github.com/spf13/cobra"
"go.uber.org/zap"
"net/http"
"os"
"os/signal"
"syscall"
)
// svrCmd represents the svr command
// go build -ldflags "-w -s" -o packet-admin.out . && ./packet-admin.out svr
var svrCmd = &cobra.Command{
Use: "svr",
Short: "server run",
Long: `server rundefault on ` + model.DefaultServerAddress,
Run: RunSvr,
}
func init() {
rootCmd.AddCommand(svrCmd)
}
// RunSvr 启动 server
func RunSvr(_ *cobra.Command, _ []string) {
if err := InitServer(); err != nil {
zap.S().Panicf("init svr err, cause: %v", err)
}
runHttpServer()
}
func runHttpServer() {
var httpServer *http.Server
ctx, cancel := context.WithCancel(context.Background())
defer func() {
if httpServer == nil {
return
}
err := httpServer.Shutdown(ctx)
if err != nil {
zap.S().Errorf("server stop error(%v)", err)
}
}()
defer func() {
select {
case <-ctx.Done():
default:
cancel()
}
}()
config := config.GetConfig()
2023-02-03 16:18:31 +08:00
if config == nil || config.Svr == nil {
zap.S().Panic("server config nil!", ErrorInitFundamental)
}
httpServer = server.RunServer(config, cancel)
SignalWatchWithContext(ctx, cancel)
}
func SignalWatchWithContext(ctx context.Context, cancel context.CancelFunc) {
sigterm := make(chan os.Signal, 1)
signal.Notify(sigterm, syscall.SIGINT, syscall.SIGTERM)
select {
case <-ctx.Done():
zap.S().Infof("terminating: context cancelled")
case <-sigterm:
cancel()
zap.S().Infof("terminating: via signal")
}
}
func SignalWatch() {
sigterm := make(chan os.Signal, 1)
sig := <-sigterm
zap.S().Infof("terminating: via signal, %v", sig)
}