12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788 |
- package services
- import (
- "fmt"
- "log"
- "os"
- "path/filepath"
- "xg_dba/api"
- "xg_dba/internal/global"
- "github.com/spf13/viper"
- )
- func SetConnectInfo_service(connectInfos []api.ConnectInfoRequest, saveFilePath string) error {
-
- dirPath := filepath.Dir(saveFilePath)
- if err := os.MkdirAll(dirPath, os.ModePerm); err != nil {
- log.Println("创建目录失败", err)
- return err
- }
-
- if _, err := os.Stat(saveFilePath); os.IsNotExist(err) {
- file, err := os.Create(saveFilePath)
- if err != nil {
- log.Println("创建文件失败", err)
- return err
- }
- defer file.Close()
- }
-
- viper.SetConfigFile(saveFilePath)
- viper.SetConfigType("toml")
-
- if err := viper.ReadInConfig(); err != nil {
- if _, ok := err.(viper.ConfigFileNotFoundError); !ok {
- log.Println("读取配置文件失败", err)
- return err
- }
- }
-
- for idx, connectInfo := range connectInfos {
-
-
-
-
-
-
-
-
- group := map[string]interface{}{
- "db_database": connectInfo.Db.Database,
- "db_password": connectInfo.Db.Password,
- "db_port": connectInfo.Db.Port,
- "db_user": connectInfo.Db.User,
- "ssh_ip": connectInfo.Ssh.Host,
- "ssh_password": connectInfo.Ssh.Password,
- "ssh_port": connectInfo.Ssh.Port,
- "ssh_username": connectInfo.Ssh.Username,
- }
-
- for key, value := range group {
- viper.Set(fmt.Sprintf("server_db.%d.%s", idx+1, key), value)
- }
- }
-
- if err := viper.WriteConfigAs(saveFilePath); err != nil {
- log.Println("写入配置文件失败", err)
- return err
- }
-
- if err := global.Cache.RefreshCache(); err != nil {
- log.Println("写入缓存失败", err)
- return err
- }
- fmt.Println("缓存刷新: ", global.Cache.Cache)
- return nil
- }
|