-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
62 lines (54 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
package main
import (
"encoding/json"
"fmt"
"log"
"net/http"
"slices"
"github.com./gorilla/mux"
"github.com./webbben/code-exec-microservice/execute"
)
type ExecRequest struct {
Code string `json:"code"`
Lang string `json:"lang"`
}
type ExecResponse struct {
Output string `json:"output"`
Error bool `json:"error"`
}
var supportedLangs = []string{"python", "go", "bash"}
func main() {
r := mux.NewRouter()
// TODO implement authentication to limit who can use this API
r.HandleFunc("/", handleExecRequest).Methods("POST")
fmt.Println("== code execution service! ==")
fmt.Println("Server listening on localhost:8081")
log.Fatal(http.ListenAndServe(":8080", r))
}
func handleExecRequest(w http.ResponseWriter, r *http.Request) {
var req ExecRequest
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
http.Error(w, fmt.Sprintf("Failed to decode request body: %s", err.Error()), http.StatusBadRequest)
return
}
if !slices.Contains(supportedLangs, req.Lang) {
http.Error(w, fmt.Sprintf("Language %s not supported", req.Lang), http.StatusBadRequest)
return
}
log.Printf("received %s code execution request", req.Lang)
output, err := execute.ExecuteCode(req.Lang, req.Code, false)
var res ExecResponse
if err != nil {
res = ExecResponse{
Output: err.Error(),
Error: true,
}
} else {
res = ExecResponse{
Output: output,
Error: false,
}
}
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(res)
}