package main
import (
"crypto/rand"
"embed"
"fmt"
"net/http"
"os"
"os/exec"
"path/filepath"
"regexp"
"github.com/gin-gonic/gin"
)
//go:embed index.html
var web embed.FS
func main() {
r := gin.Default()
r.POST("/", post)
r.GET("/", get)
r.Run(":30001")
}
func get(c *gin.Context) {
c.FileFromFS("/", http.FS(web))
}
func post(c *gin.Context) {
if c.Request.ContentLength > 100<<20 {
c.JSON(400, gin.H{
"msg": "文件太大",
})
return
}
domainPrefix := c.PostForm("t")
fileHeader, err := c.FormFile("f")
if !regexp.MustCompile("^[a-zA-Z][a-zA-Z0-9-]*$").MatchString(domainPrefix) || err != nil {
c.JSON(400, gin.H{
"msg": "域名前缀格式不对,或者没有上传文件",
})
return
}
id := rand.Text()
path := filepath.Join("/usr/local/lyz/", id)
caddy := filepath.Join("/usr/local/lyz/", id+".conf")
zipfile := filepath.Join(path, "a.zip")
domain := fmt.Sprintf("http://%s.example.com", domainPrefix)
file1 := fmt.Sprintf(`
%s {
root %s
file_server
}`, domain, path)
os.MkdirAll(path, 0o755)
c.SaveUploadedFile(fileHeader, zipfile)
defer os.Remove(zipfile)
cmd1 := fmt.Sprintf("/usr/bin/unzip %s -d %s", zipfile, path)
out, err := exec.Command("/bin/sh", "-c", cmd1).CombinedOutput()
if err != nil {
os.RemoveAll(path)
c.JSON(400, gin.H{
"msg": fmt.Sprintf("失败1: %v 输出: %s", err, out),
})
return
}
os.WriteFile(caddy, []byte(file1), 0o644)
cmd2 := fmt.Sprintf("/usr/bin/caddy reload --config /etc/caddy/Caddyfile --force")
out, err = exec.Command("/bin/sh", "-c", cmd2).CombinedOutput()
if err != nil {
os.RemoveAll(path)
os.Remove(caddy)
c.JSON(400, gin.H{
"msg": fmt.Sprintf("失败2: %v 输出: %s", err, out),
})
return
}
c.JSON(200, gin.H{
"msg": domain,
})
}