55 lines
1.2 KiB
Go
55 lines
1.2 KiB
Go
package handlers
|
|
|
|
import (
|
|
"context"
|
|
"time"
|
|
|
|
"github.com/gin-gonic/gin"
|
|
"github.com/niangaodev/art-code/runner"
|
|
"github.com/niangaodev/art-code/utils"
|
|
)
|
|
|
|
type RunCodeRequest struct {
|
|
Language string `json:"language" binding:"required"`
|
|
Code string `json:"code" binding:"required"`
|
|
}
|
|
|
|
func RunCode(c *gin.Context) {
|
|
var req RunCodeRequest
|
|
if err := c.ShouldBindJSON(&req); err != nil {
|
|
utils.Error(c, 400, "Invalid request")
|
|
return
|
|
}
|
|
|
|
// 对于前端语言,直接返回代码供前端渲染,或者提示不支持后端执行
|
|
switch req.Language {
|
|
case "html", "vue", "react", "css":
|
|
utils.Success(c, gin.H{
|
|
"output": req.Code, // 或者返回 "Client-side rendering only"
|
|
"isClient": true,
|
|
})
|
|
return
|
|
}
|
|
|
|
// 获取运行器
|
|
r, err := runner.GetRunner(req.Language)
|
|
if err != nil {
|
|
utils.Error(c, 400, err.Error())
|
|
return
|
|
}
|
|
|
|
// 设置超时上下文 (例如 5 秒)
|
|
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
|
|
defer cancel()
|
|
|
|
// 执行代码
|
|
result, err := r.Run(ctx, req.Code)
|
|
if err != nil {
|
|
// 运行错误(如无法启动进程)
|
|
utils.ServerError(c, err)
|
|
return
|
|
}
|
|
|
|
utils.Success(c, result)
|
|
}
|