base_command.go 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. package cmd
  2. import (
  3. "context"
  4. "fmt"
  5. "github.com/gin-gonic/gin"
  6. "github.com/spf13/cobra"
  7. "log"
  8. "net/http"
  9. "os"
  10. "os/signal"
  11. "ppgo/common"
  12. "syscall"
  13. "time"
  14. )
  15. // RootCmd represents the base command when called without any subcommands
  16. var RootCmd = &cobra.Command{
  17. Use: "web",
  18. Short: "welcome use ppgo",
  19. // Uncomment the following line if your bare application
  20. // has an action associated with it:
  21. // Run: func(cmd *cobra.Command, args []string) { },
  22. }
  23. // Execute adds all child commands to the root command and sets flags appropriately.
  24. // This is called by main.main(). It only needs to happen once to the RootCmd.
  25. func Execute() {
  26. cobra.CheckErr(RootCmd.Execute())
  27. }
  28. func init() {
  29. RootCmd.PersistentFlags().StringVarP(&common.Env, "env", "e", "local", "系统环境,支持local dev")
  30. }
  31. func startHttp(r *gin.Engine, port string) {
  32. server := http.Server{
  33. Addr: fmt.Sprintf(":%s", port),
  34. Handler: r,
  35. }
  36. go func() {
  37. if err := server.ListenAndServe(); err != nil && err != http.ErrServerClosed {
  38. common.GetLog("common").Printf("server listen err:%s", err)
  39. }
  40. }()
  41. quit := make(chan os.Signal, 1)
  42. signal.Notify(quit, syscall.SIGINT, syscall.SIGTERM)
  43. <-quit
  44. ctx, channel := context.WithTimeout(context.Background(), 5*time.Second)
  45. defer channel()
  46. if err := server.Shutdown(ctx); err != nil {
  47. log.Fatal("server shutdown error")
  48. }
  49. common.GetLog("common").Println("server exiting...")
  50. }