From 0f24c2f849a9ff87da61a4f39db3cec422bc8c80 Mon Sep 17 00:00:00 2001 From: wwqgtxx Date: Tue, 14 Mar 2023 22:18:55 +0800 Subject: [PATCH] chore: add /restart to restful api --- hub/route/restart.go | 53 ++++++++++++++++++++++++++++++++++++++++++++ hub/route/server.go | 1 + 2 files changed, 54 insertions(+) create mode 100644 hub/route/restart.go diff --git a/hub/route/restart.go b/hub/route/restart.go new file mode 100644 index 00000000..196896a3 --- /dev/null +++ b/hub/route/restart.go @@ -0,0 +1,53 @@ +package route + +import ( + "fmt" + "net/http" + "os" + "os/exec" + "runtime" + "syscall" + + "github.com/Dreamacro/clash/log" + + "github.com/go-chi/chi/v5" + "github.com/go-chi/render" +) + +func restartRouter() http.Handler { + r := chi.NewRouter() + r.Post("/", restart) + return r +} + +func restart(w http.ResponseWriter, r *http.Request) { + // modify from https://github.com/AdguardTeam/AdGuardHome/blob/595484e0b3fb4c457f9bb727a6b94faa78a66c5f/internal/home/controlupdate.go#L180 + execPath, err := os.Executable() + if err != nil { + render.Status(r, http.StatusInternalServerError) + render.JSON(w, r, newError(fmt.Sprintf("getting path: %s", err))) + return + } + + if runtime.GOOS == "windows" { + cmd := exec.Command(execPath, os.Args[1:]...) + log.Infoln("restarting: %q %q", execPath, os.Args[1:]) + cmd.Stdin = os.Stdin + cmd.Stdout = os.Stdout + cmd.Stderr = os.Stderr + err = cmd.Start() + if err != nil { + log.Fatalln("restarting:: %s", err) + } + + os.Exit(0) + } + + log.Infoln("restarting: %q %q", execPath, os.Args[1:]) + err = syscall.Exec(execPath, os.Args, os.Environ()) + if err != nil { + log.Fatalln("restarting: %s", err) + } + + render.JSON(w, r, render.M{"status": "ok"}) +} diff --git a/hub/route/server.go b/hub/route/server.go index 2ce4ba8c..054b1ad1 100644 --- a/hub/route/server.go +++ b/hub/route/server.go @@ -86,6 +86,7 @@ func Start(addr string, tlsAddr string, secret string, r.Mount("/providers/rules", ruleProviderRouter()) r.Mount("/cache", cacheRouter()) r.Mount("/dns", dnsRouter()) + r.Mount("/restart", restartRouter()) }) if uiPath != "" {