package command import ( "fmt" "gitee.ltd/lxh/logger/log" "os" "os/exec" "strings" "wireguard-ui/service" ) // 分隔符 // getConfigFileName // @description: 获取服务端配置文件名称 // @return string func getConfigFileName(filePath string) string { if filePath != "" { filePath = strings.Split(filePath, string(os.PathSeparator))[len(strings.Split(filePath, string(os.PathSeparator)))-1] // 这里取到的是wg0.conf filePath = strings.Split(filePath, ".conf")[0] // 这里取到的就是wg0 return filePath } data, err := service.Setting().GetWGSetForConfig() if err != nil { log.Errorf("获取服务端配置失败: %v", err.Error()) return "" } if data.ConfigFilePath != "" { data.ConfigFilePath = strings.Split(data.ConfigFilePath, "/")[len(strings.Split(data.ConfigFilePath, "/"))-1] // 这里取到的是wg0.conf data.ConfigFilePath = strings.Split(data.ConfigFilePath, ".conf")[0] // 这里取到的就是wg0 } return data.ConfigFilePath } // RestartWireguard // @description: 是否重启 // @param isAsync // 是否异步执行 func RestartWireguard(isAsync bool, filePath string) { if isAsync { go func() { StopWireguard(filePath) // 停止 StartWireguard(filePath) // 启动 }() } else { StopWireguard(filePath) // 停止 StartWireguard(filePath) // 启动 } return } // StopWireguard // @description: 停止服务端 func StopWireguard(filePath string) { configFileName := getConfigFileName(filePath) cmd := exec.Command("/bin/sh", "-c", fmt.Sprintf("wg-quick down %s", configFileName)) if err := cmd.Run(); err == nil { log.Infof("停止wireguard[%s]服务端成功", configFileName) } return } // StartWireguard // @description: 启动服务端 func StartWireguard(filePath string) { configFileName := getConfigFileName(filePath) cmd := exec.Command("/bin/sh", "-c", fmt.Sprintf("wg-quick up %s", configFileName)) if err := cmd.Run(); err == nil { log.Infof("启动wireguard[%s]服务端成功", configFileName) } return }