-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
73 lines (57 loc) · 1.46 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
package main
import (
"bytes"
"os/exec"
"time"
"github.com/gofiber/fiber/v2"
)
// Request structure to receive code execution requests
type ExecuteRequest struct {
Code string `json:"code"`
}
// Response structure to send back execution results
type ExecuteResponse struct {
Status string `json:"status"`
Result string `json:"result"`
}
func executeCode(c *fiber.Ctx) error {
req := new(ExecuteRequest)
if err := c.BodyParser(req); err != nil {
return c.Status(fiber.StatusBadRequest).JSON(fiber.Map{"error": "cannot parse request"})
}
cmd := exec.Command("python", "-c", req.Code)
var out bytes.Buffer
cmd.Stdout = &out
cmd.Stderr = &out
// Set a 5-second timeout for code execution
err := runCmdWithTimeout(cmd, 5*time.Second)
resp := new(ExecuteResponse)
if err != nil {
resp.Status = "error"
resp.Result = err.Error() + ": " + out.String()
} else {
resp.Status = "success"
resp.Result = out.String()
}
return c.JSON(resp)
}
// runCmdWithTimeout runs the given command with a specified timeout duration.
func runCmdWithTimeout(cmd *exec.Cmd, timeout time.Duration) error {
if err := cmd.Start(); err != nil {
return err
}
done := make(chan error)
go func() { done <- cmd.Wait() }()
select {
case <-time.After(timeout):
cmd.Process.Kill()
return exec.ErrNotFound // You can define a custom error for timeout
case err := <-done:
return err
}
}
func main() {
app := fiber.New()
app.Post("/execute", executeCode)
app.Listen(":8888")
}