86 lines
1.7 KiB
Go
86 lines
1.7 KiB
Go
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 run,default 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)
|
||
}
|