共计 1515 个字符,预计需要花费 4 分钟才能阅读完成。
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")
}
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<title> 上传文件示例 </title>
</head>
<body>
<form action="/upload" method="post" enctype="multipart/form-data">
<input type="file" name="yaml">
<input type="submit" value="上传">
</form>
</body>
</html>
正文完
发表至: k8s-operator
2023-03-28