-
Notifications
You must be signed in to change notification settings - Fork 0
/
webserver.go
92 lines (73 loc) · 1.5 KB
/
webserver.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
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
package main
import (
"net/http"
"os"
"os/exec"
"strings"
"io/ioutil"
)
var addr = "localhost:8080"
func enableCors(w *http.ResponseWriter) {
(*w).Header().Set("Access-Control-Allow-Origin", "*")
}
func main() {
if a := os.Getenv("ADDR"); a != "" {
addr = a
}
http.HandleFunc("/", api)
if err := http.ListenAndServe(addr, nil); err != nil {
println(err.Error())
os.Exit(1)
}
}
func check(e error) {
if e != nil {
panic(e)
}
}
func api(w http.ResponseWriter, r *http.Request) {
enableCors(&w)
var command string
if r.Method == "GET" || r.Method == "POST" {
command = r.FormValue("command")
if command == "" {
w.WriteHeader(http.StatusBadRequest)
w.Write([]byte("?command= cannot be empty"))
}
}
switch r.Method {
case "GET":
path, err := exec.LookPath(strings.Fields(command)[0])
if err != nil {
w.WriteHeader(http.StatusBadRequest)
w.Write([]byte(err.Error()))
return
}
w.WriteHeader(http.StatusOK)
w.Write([]byte(path))
case "POST":
var (
parts = strings.Fields(command)
command = parts[0]
args = []string{}
)
if command == "read" {
dat, err := ioutil.ReadFile(parts[1])
check(err)
w.Write([]byte(string(dat)))
}
if len(parts) > 1 {
args = parts[1:]
}
cmd := exec.Command(command, args...)
if err := cmd.Start(); err != nil {
w.WriteHeader(http.StatusBadRequest)
w.Write([]byte(err.Error()))
return
}
w.WriteHeader(200)
default:
w.WriteHeader(404)
w.Write([]byte("GET/POST only"))
}
}