package middleware import ( "fmt" "os" "path/filepath" "regexp" "sort" "xg_dba/internal/models" "github.com/BurntSushi/toml" ) func Cache() { // 指定需要查找的根文件夹路径 folderPath := "C:\\Program_GT\\Code\\Go\\Work\\xugu\\xg_dba\\config" packageModels := make(map[string]models.Cache) err := filepath.Walk(folderPath, func(path string, info os.FileInfo, err error) error { if err != nil { return err } if info.IsDir() { listenFilePath := filepath.Join(path, "listen.toml") var connectInfo models.ConnectInfo var systemMetaInfo models.SystemMetaInfo if fileExists(listenFilePath) { if _, err := parseTomlFile(listenFilePath, &connectInfo); err != nil { return err } } latestOsInfoFilePath, err := getLatestOsInfoFile(path) if err != nil { return err } if latestOsInfoFilePath != "" { if _, err := parseTomlFile(latestOsInfoFilePath, &systemMetaInfo); err != nil { return err } } host := connectInfo.Ssh.Host if host != "" { packageModels[host] = models.Cache{ ConnectInfo: connectInfo, SystemMetaInfo: systemMetaInfo, } } } return nil }) if err != nil { fmt.Printf("Error walking the path %q: %v\n", folderPath, err) return } for host, cache := range packageModels { fmt.Printf("Host: %s, Cache: %+v\n", host, cache) } } func fileExists(filename string) bool { info, err := os.Stat(filename) if os.IsNotExist(err) { return false } return !info.IsDir() } func parseTomlFile(filePath string, v interface{}) (toml.MetaData, error) { file, err := os.Open(filePath) if err != nil { return toml.MetaData{}, err } defer file.Close() decoder := toml.NewDecoder(file) metaData, err := decoder.Decode(v) if err != nil { return toml.MetaData{}, err } return metaData, nil } func getLatestOsInfoFile(dirPath string) (string, error) { pattern := regexp.MustCompile(`^os_info(?:_\d{8}_\d{6})?\.toml$`) files, err := os.ReadDir(dirPath) if err != nil { return "", err } var matchingFiles []string for _, file := range files { if !file.IsDir() && pattern.MatchString(file.Name()) { matchingFiles = append(matchingFiles, filepath.Join(dirPath, file.Name())) } } if len(matchingFiles) == 0 { return "", nil } sort.Slice(matchingFiles, func(i, j int) bool { return matchingFiles[i] > matchingFiles[j] }) return matchingFiles[0], nil }