package main
import (
"bytes"
"io/ioutil"
"net/http"
"os"
"os/exec"
_ "path/filepath"
"github.com/gin-gonic/gin"
_ "gopkg.in/yaml.v3"
"gorm.io/driver/mysql"
"gorm.io/gorm"
)
type YAML struct {
Content string `gorm:"type:text"`
}
func main() {
// 初始化数据库
dsn := "root:xixu@tcp(10.23.18x.x1:3306)/texxt?charset=utf8mb4&parseTime=True&loc=Local"
db, err := gorm.Open(mysql.Open(dsn), &gorm.Config{})
if err != nil {
panic(any("Failed to connect database"))
}
db.AutoMigrate(&YAML{})
// 初始化 Gin 路由
r := gin.Default()
r.LoadHTMLGlob("./temp/*")
r.GET("/upload", func(c *gin.Context) {
c.HTML(http.StatusOK, "upload.html", gin.H{
"mess": "mess",
})
})
r.POST("/upload", func(c *gin.Context) {
// 从 HTTP 请求中读取 YAML 文件内容
file, err := c.FormFile("yaml")
if err != nil {
c.String(http.StatusBadRequest, "Bad request")
return
}
f, err := file.Open()
if err != nil {
c.String(http.StatusBadRequest, "Bad request")
return
}
defer f.Close()
content, err := ioutil.ReadAll(f)
if err != nil {
c.String(http.StatusBadRequest, "Bad request")
return
}
// 将 YAML 文件内容存储到数据库中
yaml := YAML{Content: string(content)}
db.Create(&yaml)
// 应用 YAML 文件内容到 Kubernetes 集群中
cmd := exec.Command("kubectl", "apply", "-f", "-")
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
cmd.Stdin = bytes.NewBufferString(yaml.Content)
err = cmd.Run()
if err != nil {
c.String(http.StatusInternalServerError, "Internal server error")
return
}
c.String(http.StatusOK, "YAML file uploaded successfully")
})
r.Run(":8080")
}
上传文件示例
服务器托管,北京服务器托管,服务器租用 http://www.fwqtg.net