You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

123 lines
2.3 KiB

package config
import (
"io"
"k8s-manager/handler/common"
"log"
"net/http"
"os"
"path/filepath"
"k8s.io/client-go/tools/clientcmd"
"github.com/gin-gonic/gin"
)
// 配置文件上传接口的handler
func Upload(ctx *gin.Context) {
// 1. 获取上传的临时文件, post/put,
tmpFile, err := ctx.FormFile("config")
if err != nil {
log.Println(err)
ctx.JSON(http.StatusOK, gin.H{
"code": 1,
"message": err.Error(),
})
return
}
// 2. 校验配置文件是否合理
// clientcmd.Validate(config)
// 打开文件,读取文件内容,加载为配置,校验合法性
// 打开文件
file, err := tmpFile.Open()
if err != nil {
log.Println(err)
ctx.JSON(http.StatusOK, gin.H{
"code": 1,
"message": err.Error(),
})
return
}
// 读取文件内容
content, err := io.ReadAll(file)
if err != nil {
log.Println(err)
ctx.JSON(http.StatusOK, gin.H{
"code": 1,
"message": err.Error(),
})
return
}
// 加载为配置
config, err := clientcmd.Load(content)
if err != nil {
log.Println(err)
ctx.JSON(http.StatusOK, gin.H{
"code": 1,
"message": err.Error(),
})
return
}
// 校验合法性
if err := clientcmd.Validate(*config); err != nil {
log.Println(err)
ctx.JSON(http.StatusOK, gin.H{
"code": 1,
"message": err.Error(),
})
return
}
// 3. 将配置文件存储在正确的位置
// 设置目标位置
//kubeConfigPath := common.KubeConfigPath
// 创建必要的目录
dir := filepath.Dir(common.KubeConfigPath)
if err := os.MkdirAll(dir, 0644); err != nil {
log.Println(err)
ctx.JSON(http.StatusOK, gin.H{
"code": 1,
"message": err.Error(),
})
return
}
// 将临时文件存储到目标位置
if err := ctx.SaveUploadedFile(tmpFile, common.KubeConfigPath); err != nil {
log.Println(err)
ctx.JSON(http.StatusOK, gin.H{
"code": 1,
"message": err.Error(),
})
return
}
// 4. 成功的响应
ctx.JSON(http.StatusOK, gin.H{
"code": 0,
"message": "config file uploaded",
})
}
func Config(ctx *gin.Context) {
// 1. 读取文件内容
content, err := os.ReadFile(common.KubeConfigPath)
if err != nil {
log.Println(err)
ctx.JSON(http.StatusOK, gin.H{
"code": 1,
"message": err.Error(),
})
return
}
// 2. 响应
ctx.JSON(http.StatusOK, gin.H{
"code": 0,
"data": string(content),
})
}