Files
elmprodvpn/selective-vpn-api/app/routes_handlers_service_action.go

84 lines
2.1 KiB
Go

package app
import (
"encoding/json"
"fmt"
"io"
"net/http"
"strings"
)
func runRoutesServiceAction(action string) cmdResult {
action = strings.ToLower(strings.TrimSpace(action))
unit := routesServiceUnitName()
if unit == "" {
return cmdResult{
OK: false,
Message: "routes service unit unresolved: set preferred iface or SELECTIVE_VPN_ROUTES_UNIT",
}
}
var args []string
switch action {
case "start", "stop", "restart":
args = []string{"systemctl", action, unit}
default:
return cmdResult{
OK: false,
Message: "unknown action (expected start|stop|restart)",
}
}
stdout, stderr, exitCode, err := runCommand(args[0], args[1:]...)
res := cmdResult{
OK: err == nil && exitCode == 0,
ExitCode: exitCode,
Stdout: stdout,
Stderr: stderr,
}
if err != nil {
res.Message = err.Error()
} else {
res.Message = fmt.Sprintf("%s done (%s)", action, unit)
}
return res
}
func makeRoutesServiceActionHandler(action string) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodPost {
http.Error(w, "method not allowed", http.StatusMethodNotAllowed)
return
}
res := runRoutesServiceAction(action)
writeJSON(w, http.StatusOK, res)
}
}
// POST /api/v1/routes/service { "action": "start|stop|restart" }
// ---------------------------------------------------------------------
// EN: `handleRoutesService` is an HTTP handler for routes service.
// RU: `handleRoutesService` - HTTP-обработчик для routes service.
// ---------------------------------------------------------------------
func handleRoutesService(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodPost {
http.Error(w, "method not allowed", http.StatusMethodNotAllowed)
return
}
var body struct {
Action string `json:"action"`
}
if r.Body != nil {
defer r.Body.Close()
_ = json.NewDecoder(io.LimitReader(r.Body, 1<<20)).Decode(&body)
}
res := runRoutesServiceAction(body.Action)
if strings.Contains(res.Message, "unknown action") {
writeJSON(w, http.StatusBadRequest, res)
return
}
writeJSON(w, http.StatusOK, res)
}