feat(docker): support C and C++ code compilation and execution in Docker environment

feat(page): redirect HomePage to playground
This commit is contained in:
ngc2207 2025-01-11 00:40:50 +08:00
parent 9deef5757d
commit eed90a9fe4
2 changed files with 22 additions and 7 deletions

View File

@ -33,9 +33,22 @@ async function prepareEnvironment(docker: Dockerode, imageGCC: string) {
async function compileAndRun( async function compileAndRun(
code: string, code: string,
language: string,
docker: Dockerode, docker: Dockerode,
imageGCC: string imageGCC: string
): Promise<Dockerode.Container> { ): Promise<Dockerode.Container> {
let compileCommand = "";
if (language === "c") {
compileCommand = `gcc main.c -o main && ./main`;
} else if (language === "cpp") {
compileCommand = `g++ main.cpp -o main && ./main`;
} else {
throw new Error("Unsupported language: " + language);
}
const extension = language === "c" ? "c" : "cpp";
const container = await docker.createContainer({ const container = await docker.createContainer({
Image: imageGCC, Image: imageGCC,
Cmd: [ Cmd: [
@ -44,7 +57,7 @@ async function compileAndRun(
`export LANG=C.UTF-8 && printf '%s' '${code.replace( `export LANG=C.UTF-8 && printf '%s' '${code.replace(
/'/g, /'/g,
"'\\''" "'\\''"
)}' > main.c && gcc main.c -o main && ./main`, )}' > main.${extension} && ${compileCommand}`,
], ],
Tty: false, Tty: false,
}); });
@ -119,9 +132,9 @@ export async function runCode(
let container: Dockerode.Container | undefined; let container: Dockerode.Container | undefined;
try { try {
if (language === "c") { if (language === "c" || language === "cpp") {
await prepareEnvironment(docker, imageGCC); await prepareEnvironment(docker, imageGCC);
container = await compileAndRun(code, docker, imageGCC); container = await compileAndRun(code, language, docker, imageGCC);
const stream = await container.attach({ const stream = await container.attach({
stream: true, stream: true,
stdout: true, stdout: true,
@ -135,13 +148,13 @@ export async function runCode(
output: result.output, output: result.output,
}; };
} else { } else {
throw new Error(`不支持的语言: ${language}`); throw new Error(`Unsupported language: ${language}`);
} }
} catch (error) { } catch (error) {
console.error("运行代码时出错:", error); console.error("Error running code:", error);
return { return {
type: "error", type: "error",
message: error instanceof Error ? error.message : "未知错误", message: error instanceof Error ? error.message : "Unknown error",
output: "", output: "",
}; };
} finally { } finally {

View File

@ -32,6 +32,8 @@
// ); // );
// } // }
import { redirect } from "next/navigation";
export default function HomePage() { export default function HomePage() {
return null; redirect("/playground");
} }