cmd_run.go 1.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. package main
  2. import (
  3. "context"
  4. "os"
  5. "os/signal"
  6. "syscall"
  7. "github.com/goccy/go-json"
  8. "github.com/sagernet/sing-box"
  9. "github.com/sagernet/sing-box/option"
  10. "github.com/sirupsen/logrus"
  11. "github.com/spf13/cobra"
  12. )
  13. var commandRun = &cobra.Command{
  14. Use: "run",
  15. Short: "run service",
  16. Run: run,
  17. }
  18. func run(cmd *cobra.Command, args []string) {
  19. configContent, err := os.ReadFile(configPath)
  20. if err != nil {
  21. logrus.Fatal("read config: ", err)
  22. }
  23. var options option.Options
  24. err = json.Unmarshal(configContent, &options)
  25. if err != nil {
  26. logrus.Fatal("decode config: ", err)
  27. }
  28. if disableColor {
  29. if options.Log == nil {
  30. options.Log = &option.LogOption{}
  31. }
  32. options.Log.DisableColor = true
  33. }
  34. ctx, cancel := context.WithCancel(context.Background())
  35. service, err := box.NewService(ctx, options)
  36. if err != nil {
  37. logrus.Fatal("create service: ", err)
  38. }
  39. err = service.Start()
  40. if err != nil {
  41. logrus.Fatal("start service: ", err)
  42. }
  43. osSignals := make(chan os.Signal, 1)
  44. signal.Notify(osSignals, os.Interrupt, syscall.SIGTERM)
  45. <-osSignals
  46. cancel()
  47. service.Close()
  48. }