Files
sing-box-extended-mirror/cmd/sing-box/cmd_run.go
T

75 lines
1.5 KiB
Go
Raw Normal View History

2022-07-04 16:45:32 +08:00
package main
import (
"context"
2022-08-12 12:13:57 +08:00
"net/http"
2022-07-04 16:45:32 +08:00
"os"
"os/signal"
"syscall"
"github.com/sagernet/sing-box"
2022-07-24 17:58:52 +08:00
"github.com/sagernet/sing-box/common/json"
2022-07-12 15:17:29 +08:00
"github.com/sagernet/sing-box/log"
2022-07-04 16:45:32 +08:00
"github.com/sagernet/sing-box/option"
2022-08-12 12:13:57 +08:00
"github.com/sagernet/sing/common/debug"
2022-08-07 14:58:07 +08:00
E "github.com/sagernet/sing/common/exceptions"
2022-07-06 15:01:09 +08:00
2022-07-04 16:45:32 +08:00
"github.com/spf13/cobra"
)
var commandRun = &cobra.Command{
Use: "run",
2022-07-04 17:08:28 +08:00
Short: "Run service",
2022-08-13 18:36:49 +08:00
Run: func(cmd *cobra.Command, args []string) {
err := run()
if err != nil {
log.Fatal(err)
}
},
2022-07-04 16:45:32 +08:00
}
2022-08-13 18:36:49 +08:00
func init() {
mainCommand.AddCommand(commandRun)
2022-08-07 14:58:07 +08:00
}
2022-08-13 18:36:49 +08:00
func run() error {
2022-07-04 16:45:32 +08:00
configContent, err := os.ReadFile(configPath)
if err != nil {
2022-08-07 14:58:07 +08:00
return E.Cause(err, "read config")
2022-07-04 16:45:32 +08:00
}
var options option.Options
err = json.Unmarshal(configContent, &options)
if err != nil {
2022-08-07 14:58:07 +08:00
return E.Cause(err, "decode config")
2022-07-04 16:45:32 +08:00
}
if disableColor {
if options.Log == nil {
2022-07-19 22:16:49 +08:00
options.Log = &option.LogOptions{}
2022-07-04 16:45:32 +08:00
}
options.Log.DisableColor = true
}
ctx, cancel := context.WithCancel(context.Background())
2022-07-07 21:47:21 +08:00
instance, err := box.New(ctx, options)
2022-07-04 16:45:32 +08:00
if err != nil {
2022-08-07 14:58:07 +08:00
cancel()
return E.Cause(err, "create service")
2022-07-04 16:45:32 +08:00
}
2022-07-07 21:47:21 +08:00
err = instance.Start()
2022-07-04 16:45:32 +08:00
if err != nil {
2022-08-07 14:58:07 +08:00
cancel()
return E.Cause(err, "start service")
2022-07-04 16:45:32 +08:00
}
2022-08-12 12:13:57 +08:00
if debug.Enabled {
http.HandleFunc("/debug/close", func(writer http.ResponseWriter, request *http.Request) {
cancel()
instance.Close()
})
}
2022-07-04 16:45:32 +08:00
osSignals := make(chan os.Signal, 1)
signal.Notify(osSignals, os.Interrupt, syscall.SIGTERM)
<-osSignals
cancel()
2022-07-07 21:47:21 +08:00
instance.Close()
2022-08-07 14:58:07 +08:00
return nil
2022-07-04 16:45:32 +08:00
}