Go语言的游乐场

这是一个使用Go语言构建的简单在线代码编译和运行平台。用户可以通过网页提交代码,服务端接收并运行代码,返回输出结果。平台使用goroutine生成唯一ID,确保每个代码文件的唯一性,并通过`os/exec`包调用`go run`命令来编译和执行代码。前端页面包含一个文本编辑器用于输入代码,一个按钮触发编译,以及一个区域显示编译输出。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

代码如下:

package main

import (
	"log"
	"net/http"
	"os"
	"os/exec"
	"strconv"
	"sync"
)

type Lockmap struct {
	sync.Mutex
	m map[string]int
}

var uniq = make(chan int)

func init() {
	go func() {
		for i := 0; ; i++ {
			uniq <- i
		}
	}()
}

func main() {
	if err := os.Chdir(os.TempDir()); err != nil {
		log.Fatal(err)
	}
	http.HandleFunc("/", FrontPage)
	http.HandleFunc("/compile", Compile)
	log.Fatal(http.ListenAndServe("127.0.0.1:1234", nil))
}
func FrontPage(w http.ResponseWriter, _ *http.Request) {
	w.Write([]byte(frontPage))
}

func err(w http.ResponseWriter, e error) bool {
	if e != nil {
		w.Write([]byte(e.Error()))
		return true
	}
	return false
}

func Compile(w http.ResponseWriter, req *http.Request) {
	x := "play_" + strconv.Itoa(<-uniq) + ".go"
	f, e := os.Create(x)
	if err(w, e) {
		return
	}
	f.Close()
	cmd := exec.Command("go", "run", x)
	o, e := cmd.CombinedOutput()
	if err(w, e) {
		return
	}
	w.Write(o)
}

const frontPage = `<!doctype html>
<html><head>
<script>
var req;
function compile(){
	var prog=document.getElementById("edit").value;
	var req=new XMLHttpRequest();
	req.onreadystatechange=function(){
		if(!req||req.readyState!=4)
			return
		document.getElementById("output").innerHTML=req.responseText;
	}
	req.open("POST","/compile",ture);
	req.setRequestHeader("Content-Type","text/plain;charset=utf-8");
	req.send(prog);
}
</script>
</head>
<body>
<textarea rows="25" cols="80" id="edit" spellcheck="false">
package main
import "fmt"
func main(){
	fmt.Println("Hello World")
}
</textarea>
<button onclick="compile();">run</button>
<div id="output"></div>
</body>
</html>
`

http://localhost:1234

访问失败。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值