-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.go
More file actions
73 lines (61 loc) · 1.73 KB
/
server.go
File metadata and controls
73 lines (61 loc) · 1.73 KB
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 (
"encoding/json"
"io"
"log"
"net/http"
"os"
"os/exec"
)
func enableCors(w *http.ResponseWriter) {
(*w).Header().Set("Access-Control-Allow-Origin", "*")
(*w).Header().Set("Access-Control-Allow-Methods", "POST, OPTIONS")
(*w).Header().Set("Access-Control-Allow-Headers", "Content-Type")
}
func handleParse(w http.ResponseWriter, r *http.Request) {
enableCors(&w)
if r.Method == http.MethodOptions {
w.WriteHeader(http.StatusOK)
return
}
if r.Method != http.MethodPost {
http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
return
}
var req struct {
Code string `json:"code"`
}
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
http.Error(w, "Invalid request body", http.StatusBadRequest)
return
}
tmpfile, err := os.CreateTemp("", "code-*.rb")
if err != nil {
http.Error(w, "Failed to create temporary file", http.StatusInternalServerError)
return
}
defer os.Remove(tmpfile.Name())
if _, err := tmpfile.Write([]byte(req.Code)); err != nil {
http.Error(w, "Failed to write to temporary file", http.StatusInternalServerError)
return
}
if err := tmpfile.Close(); err != nil {
http.Error(w, "Failed to close temporary file", http.StatusInternalServerError)
return
}
cmd := exec.Command("stree", "json", tmpfile.Name())
output, err := cmd.Output()
if err != nil {
http.Error(w, "Failed to execute stree command", http.StatusInternalServerError)
return
}
w.Header().Set("Content-Type", "application/json")
if _, err := io.WriteString(w, string(output)); err != nil {
log.Printf("Error writing response: %v", err)
}
}
func main() {
http.HandleFunc("/parse", handleParse)
log.Println("Server starting on :4000")
log.Fatal(http.ListenAndServe(":4000", nil))
}