Skip to content

Commit

Permalink
Finally running code
Browse files Browse the repository at this point in the history
  • Loading branch information
slashexx committed Nov 4, 2024
1 parent 5f7c702 commit a5e5472
Show file tree
Hide file tree
Showing 4 changed files with 66 additions and 52 deletions.
3 changes: 1 addition & 2 deletions backend/api-gateway/main.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
// First ever comment from KDE let's go ?
package main

import (
"bytes"
"encoding/json"
Expand Down Expand Up @@ -73,6 +72,6 @@ func executeCode(w http.ResponseWriter, r *http.Request) {

func main() {
http.HandleFunc("/execute", executeCode)
fmt.Println("API Gateway running on port 8080\n")
fmt.Println("API Gateway running on port 8080")
log.Fatal(http.ListenAndServe(":8080", nil))
}
3 changes: 3 additions & 0 deletions backend/code-execution-service/Dockerfile
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,9 @@ RUN apk add --no-cache \
openjdk11 \
bash

# Check if javac is installed
RUN javac -version || echo "javac not found"

WORKDIR /app

# Copy go.mod and main.go to download dependencies
Expand Down
105 changes: 58 additions & 47 deletions backend/code-execution-service/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,11 +7,12 @@ import (
"net/http"
"os"
"os/exec"
"path/filepath"
)

type Request struct {
Language string `json:"language"`
Code string `json:"code"`
Code string `json:"code"`
}

type Response struct {
Expand All @@ -24,7 +25,6 @@ func executeCode(language string, code string) (string, error) {
var tmpFile *os.File
var err error

// Create a temporary file
tmpFile, err = os.CreateTemp("", "*."+language)
if err != nil {
return "", err
Expand All @@ -35,44 +35,58 @@ func executeCode(language string, code string) (string, error) {
}
}()

// Write the code to the temporary file
if _, err := tmpFile.Write([]byte(code)); err != nil {
return "", err
}
tmpFile.Close()


switch language {
case "go":
fmt.Println("Go file name is :"+tmpFile.Name())
cmd = exec.Command("go", "run", tmpFile.Name())
case "python":
cmd = exec.Command("python3", tmpFile.Name())
case "c":
execCmd := exec.Command("gcc", tmpFile.Name(), "-o", tmpFile.Name()[:len(tmpFile.Name())-2])
execCmd := exec.Command("gcc", tmpFile.Name(), "-o", tmpFile.Name()[:len(tmpFile.Name())-2])
if err := execCmd.Run(); err != nil {
cmdOutput, _ := execCmd.CombinedOutput()
cmdOutput, _ := execCmd.CombinedOutput()
return string(cmdOutput), err
}
cmd = exec.Command(tmpFile.Name()[:len(tmpFile.Name())-2])
cmd = exec.Command(tmpFile.Name()[:len(tmpFile.Name())-2])
case "cpp":
execCmd := exec.Command("g++", tmpFile.Name(), "-o", tmpFile.Name()[:len(tmpFile.Name())-4])
execCmd := exec.Command("g++", tmpFile.Name(), "-o", tmpFile.Name()[:len(tmpFile.Name())-4])
if err := execCmd.Run(); err != nil {
cmdOutput, _ := execCmd.CombinedOutput()
cmdOutput, _ := execCmd.CombinedOutput()
return string(cmdOutput), err
}
cmd = exec.Command(tmpFile.Name()[:len(tmpFile.Name())-4]) // Execute the compiled binary
cmd = exec.Command(tmpFile.Name()[:len(tmpFile.Name())-4])
case "java":
execCmd := exec.Command("javac", tmpFile.Name())
if err := execCmd.Run(); err != nil {

cmdOutput, _ := execCmd.CombinedOutput()
tmpFileName := filepath.Join(os.TempDir(), "Main.java") // Ensure consistent file name
tmpFile, err = os.Create(tmpFileName)
if err != nil {
return "", err
}
defer os.Remove(tmpFileName) // Cleanup the file

// Write the Java code to the file
if _, err := tmpFile.Write([]byte(code)); err != nil {
return "", err
}
tmpFile.Close() // Close the file to ensure it is written before compiling

// Compile the Java file
fmt.Printf("Compiling with command: %s %s\n", "javac", tmpFileName)
execCmd := exec.Command("javac", tmpFileName)
cmdOutput, err := execCmd.CombinedOutput()
if err != nil {
return string(cmdOutput), err
}
className := tmpFile.Name()[:len(tmpFile.Name())-5]

// Execute the Java program
className := "Main"
cmd = exec.Command("java", className)


cmdOutput, err := cmd.CombinedOutput()
cmd.Dir = filepath.Dir(tmpFileName) // Set the working directory
cmdOutput, err = cmd.CombinedOutput()
if err != nil {
return string(cmdOutput), err
}
Expand All @@ -82,44 +96,41 @@ func executeCode(language string, code string) (string, error) {
return "", fmt.Errorf("unsupported language: %s", language)
}

// Execute the command and capture output
cmdOutput, err := cmd.CombinedOutput()
return string(cmdOutput), err
}


func enableCors(w http.ResponseWriter) {
w.Header().Set("Access-Control-Allow-Origin", "http://localhost:8080")
w.Header().Set("Access-Control-Allow-Methods", "POST, OPTIONS")
w.Header().Set("Access-Control-Allow-Headers", "Content-Type")
w.Header().Set("Access-Control-Allow-Origin", "http://localhost:8080")
w.Header().Set("Access-Control-Allow-Methods", "POST, OPTIONS")
w.Header().Set("Access-Control-Allow-Headers", "Content-Type")
}

func executeHandler(w http.ResponseWriter, r *http.Request) {
fmt.Printf("Received %s request for %s\n", r.Method, r.URL.Path)
enableCors(w)

if r.Method == http.MethodOptions {

w.WriteHeader(http.StatusOK)
return
}

var req Request
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}

output, err := executeCode(req.Language, req.Code)
res := Response{Output: output}
if err != nil {
res.Error = err.Error()
}

w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(res)
}
fmt.Printf("Received %s request for %s\n", r.Method, r.URL.Path)
enableCors(w)

if r.Method == http.MethodOptions {

w.WriteHeader(http.StatusOK)
return
}

var req Request
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}

output, err := executeCode(req.Language, req.Code)
res := Response{Output: output}
if err != nil {
res.Error = err.Error()
}

w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(res)
}

func main() {
http.HandleFunc("/execute", executeHandler)
Expand Down
7 changes: 4 additions & 3 deletions frontend/src/App.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -11,16 +11,18 @@ import {
} from "lucide-react";
import { useNavigate } from "react-router-dom";

type Language = "cpp" | "python" | "java" | "go";
type Language = "c" | "cpp" | "python" | "java" | "go";

const INITIAL_CODE: Record<Language, string> = {
c: '#include <stdio.h> \n\nint main() {\n printf("Hello world !"); \n return 0; \n}',
cpp: '#include <iostream>\n\nint main() {\n std::cout << "Hello, World!" << std::endl;\n return 0;\n}',
python: 'print("Hello, World!")',
java: 'public class Main {\n public static void main(String[] args) {\n System.out.println("Hello, World!");\n }\n}',
go: 'package main\n\nimport "fmt"\n\nfunc main() {\n fmt.Println("Hello, World!")\n}',
};

const LANGUAGE_CONFIGS = {
c: { label: 'C', icon:Cpu, color: "text-blue-500"},
cpp: { label: "C++", icon: Cpu, color: "text-blue-500" },
python: { label: "Python", icon: Code2, color: "text-yellow-500" },
java: { label: "Java", icon: Terminal, color: "text-red-500" },
Expand All @@ -31,8 +33,7 @@ function App() {
const [selectedLanguage, setSelectedLanguage] = useState<Language>("go");
const [code, setCode] = useState(INITIAL_CODE[selectedLanguage]);
const [output, setOutput] = useState("Output will appear here...");
const [editorInstance, setEditorInstance] =
useState<monaco.editor.IStandaloneCodeEditor>(null);
const [editorInstance, setEditorInstance] = useState<monaco.editor.IStandaloneCodeEditor>(null);
const navigate = useNavigate();

const handleLanguageChange = (language: Language) => {
Expand Down

0 comments on commit a5e5472

Please sign in to comment.