viper-app/cmd/svr.go
2023-02-03 16:18:31 +08:00

86 lines
1.7 KiB
Go
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

package cmd
import (
"context"
"github.com/spf13/cobra"
"go.uber.org/zap"
"net/http"
"os"
"os/signal"
"packet-ui/internal/model"
"packet-ui/internal/server"
"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 := model.GetConfig()
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)
}