初始化
This commit is contained in:
54
server/handlers/runner.go
Normal file
54
server/handlers/runner.go
Normal file
@@ -0,0 +1,54 @@
|
||||
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)
|
||||
}
|
||||
Reference in New Issue
Block a user