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

View File

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