| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659 |
- // ============================================================================
- // cmd/toolbox-service/main.go — 独立服务模式程序(无 GUI 依赖)
- //
- // 与主程序完全分离的最小实现:不链接 Wails、Gin、beeep/Toast、systray 等
- // 任何 GUI 组件,仅用标准库 + golang.org/x/sys/windows/svc。
- // 供 Windows SCM 以 `sc create TengTuToolboxService binPath= "<exe> --service"`
- // 启动,运行电源类 HTTP API + 指令信箱 + 界面代理,常驻内存与分发体积最小。
- //
- // 构建:go build -trimpath -ldflags "-s -w" -o bin/TengTuToolbox-service.exe ./cmd/toolbox-service
- // ============================================================================
- package main
- import (
- "encoding/json"
- "fmt"
- "io"
- "log"
- "net"
- "net/http"
- "os"
- "os/exec"
- "path/filepath"
- "runtime"
- "runtime/debug"
- "strconv"
- "strings"
- "sync"
- "time"
- "unicode/utf8"
- "golang.org/x/sys/windows/svc"
- )
- const (
- serviceName = "TengTuToolboxService" // Windows 服务名(与 GUI 侧一致)
- appVersion = "0.1.11" // 应用版本(与主程序一致)
- defaultAddr = "0.0.0.0:9090" // 默认监听地址
- legacyAddr = "127.0.0.1:17891" // 旧版默认服务地址(读取时自动迁移)
- pcShutdownDelay = 30 * time.Second // 电源命令默认延迟
- xzCmdMaxLen = 200 // 指令最大长度(字符数)
- // 内存/连接约束:常驻服务保持低占用,防止堆无谓膨胀与连接池积累
- heapSoftLimitMB = 16 // GOMEMLIMIT 软上限,堆接近此值即提前 GC,避免膨胀到 40MB+
- goGCPercent = 50 // 更积极的 GC(默认 100),以 CPU 换常驻内存
- proxyTimeout = 20 * time.Second
- )
- func main() {
- // 常驻服务优先低内存:设软上限 + 更激进 GC(在 runtime 启动后尽早设置)
- debug.SetMemoryLimit(int64(heapSoftLimitMB) << 20)
- debug.SetGCPercent(goGCPercent)
- isService, err := svc.IsWindowsService()
- if err != nil {
- fmt.Println("检测服务状态失败:", err)
- os.Exit(1)
- }
- if !isService {
- fmt.Printf("这不是由 Windows 服务管理器启动的进程,请用 sc start %s 启动\n", serviceName)
- os.Exit(1)
- }
- if err := svc.Run(serviceName, &toolboxService{}); err != nil {
- os.Exit(1)
- }
- }
- // toolboxService SCM 服务实现:启动电源 API,收到 Stop/Shutdown 平滑退出
- type toolboxService struct{}
- func (s *toolboxService) Execute(_ []string, requests <-chan svc.ChangeRequest, status chan<- svc.Status) (bool, uint32) {
- status <- svc.Status{State: svc.StartPending}
- setupServiceLog()
- srv := startServicePowerAPI(serviceListenAddr())
- status <- svc.Status{State: svc.Running, Accepts: svc.AcceptStop | svc.AcceptShutdown}
- for req := range requests {
- switch req.Cmd {
- case svc.Interrogate:
- status <- req.CurrentStatus
- case svc.Stop, svc.Shutdown:
- status <- svc.Status{State: svc.StopPending}
- stopServicePowerAPI(srv)
- return false, 0
- }
- }
- stopServicePowerAPI(srv)
- return false, 0
- }
- // setupServiceLog 服务没有控制台,日志写入 %ProgramData%\TengTuToolbox\service.log
- func setupServiceLog() {
- dir := filepath.Join(os.Getenv("ProgramData"), "TengTuToolbox")
- if dir == "" || os.MkdirAll(dir, 0o755) != nil {
- return
- }
- f, err := os.OpenFile(filepath.Join(dir, "service.log"), os.O_CREATE|os.O_APPEND|os.O_WRONLY, 0o644)
- if err != nil {
- return
- }
- log.SetOutput(f)
- log.Printf("service starting: addr=%s version=%s", serviceListenAddr(), appVersion)
- }
- // serviceListenAddr 监听地址:读 %APPDATA%\TengTuToolbox\settings.json 的 serviceAddr,
- // 留空或读取失败用默认值;旧版地址自动迁移(与主程序 normalize 行为一致)。
- func serviceListenAddr() string {
- path := filepath.Join(os.Getenv("APPDATA"), "TengTuToolbox", "settings.json")
- if data, err := os.ReadFile(path); err == nil {
- var s struct {
- ServiceAddr string `json:"serviceAddr"`
- }
- if json.Unmarshal(data, &s) == nil {
- addr := strings.TrimSpace(s.ServiceAddr)
- if addr == legacyAddr {
- addr = defaultAddr
- }
- if addr != "" {
- return addr
- }
- }
- }
- return defaultAddr
- }
- // ----------------------------------------------------------------------------
- // HTTP API:仅标准库 net/http,不引入 Gin
- // ----------------------------------------------------------------------------
- // startServicePowerAPI 启动仅含电源接口的 HTTP 服务,返回句柄用于停止
- func startServicePowerAPI(addr string) *http.Server {
- mux := http.NewServeMux()
- mux.HandleFunc("/health", func(w http.ResponseWriter, r *http.Request) {
- writeJSON(w, http.StatusOK, map[string]any{"service": true, "version": appVersion, "ui": uiPeerOnline()})
- })
- mux.HandleFunc("/api/ui/register", handleUIRegister) // 界面登记自己的 API 地址
- mux.HandleFunc("/api/ui/status", handleUIStatus) // 查询界面是否在线
- // 电源接口:与界面内置 API 路径保持一致(/api/pc/* 界面版路径 与 /api/power/* 服务版路径)
- for _, prefix := range []string{"/api/power", "/api/pc"} {
- mux.HandleFunc(prefix+"/poweroff", handlePoweroff) // 30 秒后关机
- mux.HandleFunc(prefix+"/restart", handleRestart) // 30 秒后重启
- mux.HandleFunc(prefix+"/sleep", handleSleep) // 30 秒后休眠
- mux.HandleFunc(prefix+"/cancel", handleCancel) // 取消待执行命令
- mux.HandleFunc(prefix+"/status", handlePCStatus) // 查询命令状态
- }
- // 指令信箱:POST 下发,GET 读取,GET /cmd/<命令> 路径下发
- mux.HandleFunc("/api/xz/cmd", handleXZCmd) // POST=下发 / GET=取走
- mux.HandleFunc("/api/xz/cmd/", handleXZCmdPath) // 路径参数下发(URL 编码)
- mux.HandleFunc("/", proxyToUI) // 其余接口交给界面 API 处理
- // 先同步绑定:端口被占用时自动切换到备用端口(+1)
- ln, actualAddr, err := listenFirst(addr, nextPortAddr(addr))
- srv := &http.Server{
- Addr: actualAddr,
- Handler: mux,
- ReadHeaderTimeout: 10 * time.Second, // 防 slowloris,避免连接长期占住
- ReadTimeout: 30 * time.Second, // 防慢速 body 拖住连接
- WriteTimeout: 30 * time.Second, // 响应超时上限
- IdleTimeout: 60 * time.Second, // keep-alive 空闲连接回收,降低常驻连接数
- MaxHeaderBytes: 1 << 20, // 1MB 头上限,防超大头占用内存
- }
- if err != nil {
- log.Printf("service api listen failed on %s (fallback %s): %v", addr, nextPortAddr(addr), err)
- return srv // 未监听,但返回句柄供停止安全调用
- }
- if actualAddr != addr {
- log.Printf("service api fallback: %s occupied, using %s", addr, actualAddr)
- }
- log.Printf("service api listening on %s", actualAddr)
- go func() {
- if err := srv.Serve(ln); err != nil && err != http.ErrServerClosed {
- log.Printf("service api listening on %s failed: %v", actualAddr, err)
- }
- }()
- return srv
- }
- // stopServicePowerAPI 平滑关闭
- func stopServicePowerAPI(srv *http.Server) {
- if srv == nil {
- return
- }
- done := make(chan struct{})
- go func() { srv.Close(); close(done) }()
- select {
- case <-done:
- case <-time.After(5 * time.Second):
- }
- }
- // ----------------------------------------------------------------------------
- // 响应辅助:保持与原 Gin 版相同的响应格式(JSON / text)
- // ----------------------------------------------------------------------------
- func writeJSON(w http.ResponseWriter, code int, v any) {
- w.Header().Set("Content-Type", "application/json; charset=utf-8")
- w.WriteHeader(code)
- _ = json.NewEncoder(w).Encode(v)
- }
- func writeText(w http.ResponseWriter, code int, format string, args ...any) {
- w.Header().Set("Content-Type", "text/plain; charset=utf-8")
- w.WriteHeader(code)
- fmt.Fprintf(w, format, args...)
- }
- // clientIP 从 RemoteAddr 提取客户端 IP
- func clientIP(r *http.Request) string {
- host, _, err := net.SplitHostPort(r.RemoteAddr)
- if err != nil {
- return r.RemoteAddr
- }
- return host
- }
- // ----------------------------------------------------------------------------
- // 电源控制:shutdown /t 系统计时优先,休眠用 Go 计时;服务运行在 Session 0,
- // 无法弹 Toast 通知(原 GUI 版的 beeep 通知在此省略,改为写日志)
- // ----------------------------------------------------------------------------
- type pcCommand string
- const (
- pcPoweroff pcCommand = "poweroff"
- pcRestart pcCommand = "restart"
- pcSleep pcCommand = "sleep"
- )
- // PCStatus 电源命令状态快照(JSON 字段与 GUI 版一致)
- type PCStatus struct {
- Command string `json:"command"`
- Pending bool `json:"pending"`
- ExecuteAt string `json:"executeAt"`
- RemainingSecs int `json:"remainingSecs"`
- ClientIP string `json:"clientIp"`
- RequestTime string `json:"requestTime"`
- Requested bool `json:"requested"`
- }
- var (
- pcMu sync.Mutex
- pcTimer *time.Timer
- pcExecuteAt time.Time
- pcPending bool
- pcPendingCmd pcCommand
- pcSystemTimer bool // 是否已交给系统计时(shutdown /t)
- pcLastClientIP string
- pcLastTime time.Time
- pcLastCmd pcCommand
- pcRequested bool
- )
- // pcSystemCommand 构造系统命令;返回 nil 表示该命令需 Go 计时后立即执行
- func pcSystemCommand(cmd pcCommand, delaySec int) *exec.Cmd {
- switch runtime.GOOS {
- case "windows":
- switch cmd {
- case pcPoweroff:
- return exec.Command("shutdown", "/s", "/t", strconv.Itoa(delaySec), "/f")
- case pcRestart:
- return exec.Command("shutdown", "/r", "/t", strconv.Itoa(delaySec), "/f")
- }
- case "darwin":
- switch cmd {
- case pcPoweroff:
- return exec.Command("sudo", "shutdown", "-h", "+0")
- case pcRestart:
- return exec.Command("sudo", "shutdown", "-r", "+0")
- }
- case "linux":
- switch cmd {
- case pcPoweroff:
- return exec.Command("shutdown", "-h", "+0")
- case pcRestart:
- return exec.Command("shutdown", "-r", "+0")
- }
- }
- return nil
- }
- // pcExecuteNow 立即执行休眠(无系统计时,直接执行)
- func pcExecuteNow(cmd pcCommand) {
- var execCmd *exec.Cmd
- switch cmd {
- case pcSleep:
- switch runtime.GOOS {
- case "windows":
- execCmd = exec.Command("rundll32.exe", "powrprof.dll,SetSuspendState", "0,1,0")
- case "darwin":
- execCmd = exec.Command("pmset", "sleepnow")
- default:
- execCmd = exec.Command("systemctl", "suspend")
- }
- }
- if execCmd == nil {
- log.Printf("[SYS] 不支持的命令 %s (OS: %s)", cmd, runtime.GOOS)
- return
- }
- if output, err := execCmd.CombinedOutput(); err != nil {
- log.Printf("[SYS] 命令 %s 执行失败: %v | %s", cmd, err, string(output))
- } else {
- log.Printf("[SYS] 命令 %s 执行成功", cmd)
- }
- }
- // pcAbortShutdown 取消系统关机 / 重启倒计时
- func pcAbortShutdown() {
- if runtime.GOOS == "windows" {
- if output, err := exec.Command("shutdown", "/a").CombinedOutput(); err != nil {
- log.Printf("[SYS] 取消关机失败: %v | %s", err, string(output))
- } else {
- log.Println("[SYS] 系统关机已取消")
- }
- } else {
- _ = exec.Command("shutdown", "-c").Run()
- }
- }
- // getPCStatus 返回当前电源命令状态快照
- func getPCStatus() PCStatus {
- pcMu.Lock()
- defer pcMu.Unlock()
- status := PCStatus{
- Command: string(pcLastCmd),
- Pending: pcPending,
- ClientIP: pcLastClientIP,
- Requested: pcRequested,
- }
- if !pcLastTime.IsZero() {
- status.RequestTime = pcLastTime.Format("01-02 15:04:05")
- }
- if pcPending {
- status.ExecuteAt = pcExecuteAt.Format("01-02 15:04:05")
- remaining := int(time.Until(pcExecuteAt).Seconds())
- if remaining < 0 {
- remaining = 0
- }
- status.RemainingSecs = remaining
- }
- return status
- }
- // handleDelayedCommand 通用延迟命令:优先交给系统计时,不支持则用 Go 计时
- func handleDelayedCommand(w http.ResponseWriter, r *http.Request, cmd pcCommand, delay time.Duration, title string) {
- ip := clientIP(r)
- delaySec := int(delay.Seconds())
- pcMu.Lock()
- pcLastClientIP = ip
- pcLastTime = time.Now()
- pcLastCmd = cmd
- pcRequested = true
- if pcPending {
- remaining := time.Until(pcExecuteAt).Round(time.Second)
- pendingCmd := pcPendingCmd
- pcMu.Unlock()
- writeText(w, http.StatusOK, "命令 %s 已在待执行,剩余 %v\n", pendingCmd, remaining)
- return
- }
- pcPending = true
- pcPendingCmd = cmd
- pcExecuteAt = time.Now().Add(delay)
- sysCmd := pcSystemCommand(cmd, delaySec)
- if sysCmd != nil {
- pcSystemTimer = true
- pcMu.Unlock()
- if output, err := sysCmd.CombinedOutput(); err != nil {
- pcMu.Lock()
- pcPending = false
- pcPendingCmd = ""
- pcExecuteAt = time.Time{}
- pcSystemTimer = false
- pcMu.Unlock()
- log.Printf("[SYS] 命令 %s 下发失败: %v | %s", cmd, err, string(output))
- writeText(w, http.StatusInternalServerError, "命令执行失败: %v\n", err)
- return
- }
- log.Printf("[SYS] 命令 %s 交由系统计时 | %ds | 客户端 %s", cmd, delaySec, ip)
- } else {
- pcSystemTimer = false
- cmdToExec := cmd
- pcTimer = time.AfterFunc(delay, func() {
- pcMu.Lock()
- pcPending = false
- pcPendingCmd = ""
- pcMu.Unlock()
- pcExecuteNow(cmdToExec)
- })
- pcMu.Unlock()
- log.Printf("[SYS] 命令 %s 使用 Go 计时 | %ds | 客户端 %s", cmd, delaySec, ip)
- }
- writeText(w, http.StatusOK, "OK: %s\n", title)
- }
- func handlePoweroff(w http.ResponseWriter, r *http.Request) {
- handleDelayedCommand(w, r, pcPoweroff, pcShutdownDelay, "收到关机请求")
- }
- func handleRestart(w http.ResponseWriter, r *http.Request) {
- handleDelayedCommand(w, r, pcRestart, pcShutdownDelay, "收到重启请求")
- }
- func handleSleep(w http.ResponseWriter, r *http.Request) {
- handleDelayedCommand(w, r, pcSleep, pcShutdownDelay, "收到休眠请求")
- }
- // handleCancel 取消待执行命令:系统计时调 shutdown /a,Go 计时停定时器
- func handleCancel(w http.ResponseWriter, r *http.Request) {
- pcMu.Lock()
- if !pcPending {
- pcMu.Unlock()
- writeText(w, http.StatusOK, "无待执行命令\n")
- return
- }
- cancelled := pcPendingCmd
- wasSystemTimer := pcSystemTimer
- pcPending = false
- pcPendingCmd = ""
- pcExecuteAt = time.Time{}
- pcSystemTimer = false
- if pcTimer != nil {
- pcTimer.Stop()
- pcTimer = nil
- }
- pcMu.Unlock()
- if wasSystemTimer {
- pcAbortShutdown()
- }
- log.Printf("[SYS] 命令 %s 已取消 | 客户端 %s", cancelled, clientIP(r))
- writeText(w, http.StatusOK, "命令已取消\n")
- }
- func handlePCStatus(w http.ResponseWriter, r *http.Request) {
- writeJSON(w, http.StatusOK, getPCStatus())
- }
- // ----------------------------------------------------------------------------
- // 界面在线登记 + 请求代理(「服务打底 + 界面补全」)
- // ----------------------------------------------------------------------------
- var (
- uiPeerMu sync.RWMutex
- uiPeerAddr string
- uiPeerSeenAt time.Time
- // uiProxyClient 复用的转发客户端:每次请求 new http.Client 会各自创建独立
- // Transport/连接池,代理频繁时连接池资源只增不减,是常驻内存增长的来源。
- uiProxyClient = &http.Client{
- Timeout: proxyTimeout,
- Transport: &http.Transport{
- MaxIdleConns: 8, // 上限连接数,防连接池无界膨胀
- MaxIdleConnsPerHost: 4, // 单主机空闲连接上限
- IdleConnTimeout: 60 * time.Second, // 空闲连接回收
- },
- }
- )
- // uiPeerOnline 界面上次登记是否在 90 秒内(心跳 30 秒一次)
- func uiPeerOnline() bool {
- uiPeerMu.RLock()
- defer uiPeerMu.RUnlock()
- return uiPeerAddr != "" && time.Since(uiPeerSeenAt) < 90*time.Second
- }
- // handleUIRegister 界面登记/心跳:POST /api/ui/register {"addr":"127.0.0.1:17891"}
- // 仅接受本机回环请求,避免局域网内被恶意登记后劫持转发。
- func handleUIRegister(w http.ResponseWriter, r *http.Request) {
- host, _, err := net.SplitHostPort(r.RemoteAddr)
- ip := net.ParseIP(host)
- if err != nil || ip == nil || !ip.IsLoopback() {
- writeJSON(w, http.StatusForbidden, map[string]any{"error": "仅允许本机登记"})
- return
- }
- var req struct {
- Addr string `json:"addr"`
- }
- if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
- writeJSON(w, http.StatusBadRequest, map[string]any{"error": "参数格式错误"})
- return
- }
- addr := strings.TrimSpace(req.Addr)
- if _, _, err := net.SplitHostPort(addr); err != nil {
- writeJSON(w, http.StatusBadRequest, map[string]any{"error": "addr 需为 host:port"})
- return
- }
- uiPeerMu.Lock()
- uiPeerAddr = addr
- uiPeerSeenAt = time.Now()
- uiPeerMu.Unlock()
- log.Printf("ui registered: %s", addr)
- writeJSON(w, http.StatusOK, map[string]any{"ok": true})
- }
- // handleUIStatus 查询界面登记情况
- func handleUIStatus(w http.ResponseWriter, r *http.Request) {
- uiPeerMu.RLock()
- addr, seen := uiPeerAddr, uiPeerSeenAt
- uiPeerMu.RUnlock()
- writeJSON(w, http.StatusOK, map[string]any{
- "uiAddr": addr,
- "online": uiPeerOnline(),
- "lastSee": seen.Format(time.RFC3339),
- })
- }
- // proxyToUI 把服务模式未实现的请求转发给界面 API;界面未上线时返回 503
- func proxyToUI(w http.ResponseWriter, r *http.Request) {
- uiPeerMu.RLock()
- addr := uiPeerAddr
- uiPeerMu.RUnlock()
- if addr == "" || !uiPeerOnline() {
- writeJSON(w, http.StatusServiceUnavailable, map[string]any{
- "service": true,
- "error": "界面未启动或未登记,该接口暂不可用(电源类接口仍可用)",
- })
- return
- }
- target := "http://" + addr + r.URL.RequestURI()
- req, err := http.NewRequestWithContext(r.Context(), r.Method, target, r.Body)
- if err != nil {
- writeJSON(w, http.StatusBadGateway, map[string]any{"error": "构造转发请求失败"})
- return
- }
- for k, values := range r.Header {
- for _, v := range values {
- req.Header.Add(k, v)
- }
- }
- req.Header.Set("X-Forwarded-Host", r.Host)
- req.Header.Set("X-TengTu-Via", "service")
- if ip := clientIP(r); ip != "" {
- req.Header.Set("X-Forwarded-For", ip)
- }
- resp, err := uiProxyClient.Do(req)
- if err != nil {
- writeJSON(w, http.StatusBadGateway, map[string]any{"error": "界面接口无响应: " + err.Error()})
- return
- }
- defer resp.Body.Close()
- for k, values := range resp.Header {
- for _, v := range values {
- w.Header().Add(k, v)
- }
- }
- w.WriteHeader(resp.StatusCode)
- _, _ = io.Copy(w, resp.Body)
- }
- // ----------------------------------------------------------------------------
- // 指令信箱:POST /api/xz/cmd 下发指令(left / right / up / down,支持任意文本),
- // GET /api/xz/cmd 取走最近一条指令(读取后清除);GET /api/xz/cmd/<命令> 路径下发。
- // 界面在线时转发给界面(指令信箱与界面共享),离线时本地兜底。
- // ----------------------------------------------------------------------------
- var (
- xzCmdMu sync.Mutex
- xzCmdLast string
- xzCmdSeq int64
- )
- // handleXZCmd POST=下发(body {"cmd":"left"} 或 ?cmd=left),GET=取走
- func handleXZCmd(w http.ResponseWriter, r *http.Request) {
- if forwardToUI(w, r) {
- return
- }
- if r.Method == http.MethodPost {
- xzPost(w, r, strings.TrimPrefix(r.URL.Path, "/api/xz/cmd"))
- return
- }
- // GET:消费式读取,取走即清除
- xzCmdMu.Lock()
- cmd := xzCmdLast
- xzCmdLast = ""
- xzCmdMu.Unlock()
- writeText(w, http.StatusOK, "%s", cmd)
- }
- // handleXZCmdPath 路径参数下发:GET /api/xz/cmd/<命令>(URL 编码)
- func handleXZCmdPath(w http.ResponseWriter, r *http.Request) {
- if forwardToUI(w, r) {
- return
- }
- xzPost(w, r, strings.Trim(strings.TrimPrefix(r.URL.Path, "/api/xz/cmd/"), "/"))
- }
- // xzPost 校验并保存一条指令
- func xzPost(w http.ResponseWriter, r *http.Request, pathCmd string) {
- var req struct {
- Cmd string `json:"cmd"`
- }
- if err := json.NewDecoder(r.Body).Decode(&req); err != nil || strings.TrimSpace(req.Cmd) == "" {
- req.Cmd = r.URL.Query().Get("cmd") // 非 JSON 请求时回退到查询参数
- }
- if pathCmd != "" {
- req.Cmd = pathCmd // 路径参数优先
- }
- cmd := strings.TrimSpace(req.Cmd)
- if cmd == "" {
- writeJSON(w, http.StatusBadRequest, map[string]any{"error": "cmd 不能为空"})
- return
- }
- if utf8.RuneCountInString(cmd) > xzCmdMaxLen {
- writeJSON(w, http.StatusBadRequest, map[string]any{"error": fmt.Sprintf("cmd 长度不能超过 %d 个字符", xzCmdMaxLen)})
- return
- }
- xzCmdMu.Lock()
- xzCmdLast = cmd
- xzCmdSeq++
- seq := xzCmdSeq
- xzCmdMu.Unlock()
- writeJSON(w, http.StatusOK, map[string]any{"ok": true, "cmd": cmd, "seq": seq})
- }
- // forwardToUI 界面已登记在线时把请求转发给界面并返回 true
- func forwardToUI(w http.ResponseWriter, r *http.Request) bool {
- if !uiPeerOnline() {
- return false
- }
- proxyToUI(w, r)
- return true
- }
- // ----------------------------------------------------------------------------
- // 端口容错:监听地址被占用时自动切换到备用端口
- // (与根目录 apiserver_shared.go 的版本内容一致;独立二进制无法引用,故复制)
- // ----------------------------------------------------------------------------
- // listenFirst 依次尝试监听 addrs,返回第一个成功绑定的监听器及其逻辑地址。
- func listenFirst(addrs ...string) (net.Listener, string, error) {
- var lastErr error
- for _, addr := range addrs {
- ln, err := net.Listen("tcp", addr)
- if err == nil {
- return ln, addr, nil
- }
- lastErr = err
- }
- return nil, "", lastErr
- }
- // nextPortAddr 同 host 端口 +1 的备用地址;解析失败或端口越界时返回原地址。
- func nextPortAddr(addr string) string {
- host, portStr, err := net.SplitHostPort(addr)
- if err != nil {
- return addr
- }
- port, err := strconv.Atoi(portStr)
- if err != nil || port <= 0 || port >= 65535 {
- return addr
- }
- return net.JoinHostPort(host, strconv.Itoa(port+1))
- }
|