wireguard-dashboard/command/wireguard.go
2024-06-05 12:04:22 +08:00

69 lines
1.6 KiB
Go

package command
import (
"fmt"
"gitee.ltd/lxh/logger/log"
"os/exec"
"strings"
"wireguard-dashboard/repository"
)
// getConfigFileName
// @description: 获取服务端配置文件名称
// @return string
func getConfigFileName() string {
data, err := repository.System().GetServerSetting()
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) {
if isAsync {
go func() {
StopWireguard() // 停止
StartWireguard() // 启动
}()
} else {
StopWireguard() // 停止
StartWireguard() // 启动
}
return
}
// StopWireguard
// @description: 停止服务端
func StopWireguard() {
configFileName := getConfigFileName()
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() {
configFileName := getConfigFileName()
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
}