-
Notifications
You must be signed in to change notification settings - Fork 3
/
api.go
76 lines (62 loc) · 1.36 KB
/
api.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
package main
import (
"log"
"net/http"
"regexp"
"strings"
"github.com/gin-gonic/gin"
)
var (
ipFilter = regexp.MustCompile(
`rcon from \"[0-9.:]+\":`,
)
ipFilterReplace = "rcon from \"***\":"
)
func getConnect(c *gin.Context) {
if len(*flags.PublicAddress) > 0 {
c.Redirect(http.StatusTemporaryRedirect, *flags.PublicAddress)
return
}
c.String(http.StatusOK, "\"/api/connect\" disabled")
}
func getExec(c *gin.Context) {
cmd := c.DefaultQuery("cmd", "")
msg, err := exec(cmd)
if err != nil {
c.String(http.StatusBadRequest, "%v\n%v", msg, err)
return
}
c.String(http.StatusOK, msg)
}
type execModel struct {
Cmd string `json:"cmd" binding:"required"`
}
func postExec(c *gin.Context) {
var postData execModel
if err := c.ShouldBindJSON(&postData); err != nil {
c.String(http.StatusBadRequest, "%v", err)
return
}
cmd := postData.Cmd
msg, err := exec(cmd)
if err != nil {
c.String(http.StatusBadRequest, "%v\n%v", msg, err)
return
}
c.String(http.StatusOK, msg)
}
func exec(cmd string) (string, error) {
cmd = strings.TrimSpace(cmd)
if len(cmd) == 0 {
return "Error, empty command", nil
}
log.Println("cmd: ", cmd)
msg, err := client.Execute(cmd)
msg = strings.TrimSpace(msg)
log.Println("msg: ", msg)
if err != nil {
log.Println("err: ", err)
}
msg = ipFilter.ReplaceAllString(msg, ipFilterReplace)
return msg, err
}