55 lines
1.2 KiB
Go
55 lines
1.2 KiB
Go
package handlers
|
|
|
|
import (
|
|
"context"
|
|
"net/http"
|
|
"time"
|
|
|
|
"github.com/gin-gonic/gin"
|
|
"github.com/niangaodev/art-code/runner"
|
|
)
|
|
|
|
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 {
|
|
c.JSON(http.StatusBadRequest, gin.H{"error": "Invalid request"})
|
|
return
|
|
}
|
|
|
|
// 对于前端语言,直接返回代码供前端渲染,或者提示不支持后端执行
|
|
switch req.Language {
|
|
case "html", "vue", "react", "css":
|
|
c.JSON(http.StatusOK, gin.H{
|
|
"output": req.Code, // 或者返回 "Client-side rendering only"
|
|
"isClient": true,
|
|
})
|
|
return
|
|
}
|
|
|
|
// 获取运行器
|
|
r, err := runner.GetRunner(req.Language)
|
|
if err != nil {
|
|
c.JSON(http.StatusBadRequest, gin.H{"error": 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 {
|
|
// 运行错误(如无法启动进程)
|
|
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
|
return
|
|
}
|
|
|
|
c.JSON(http.StatusOK, result)
|
|
}
|