package helpers import ( "encoding/json" "log" "os" "path" "path/filepath" "recipe-manager/models" "sort" ) func ListFile(rootPath string) []string { files, err := filepath.Glob(rootPath) if err != nil { log.Panic("Error when scan recipe files:", err) } return files } func ReadFile(filePath string) (string, error) { file, err := os.ReadFile(filePath) if err != nil { log.Fatalf("Error when open file: %s", err) return "", err } return string(file), nil } func ReadRecipeFile(countryID, filePath string) *models.Recipe { if countryID == "thai" { countryID = "" } file, err := os.Open(path.Join("cofffeemachineConfig", countryID, filePath)) if err != nil { log.Fatalf("Error when open file: %s", err) return nil } defer file.Close() var data *models.Recipe err = json.NewDecoder(file).Decode(&data) if err != nil { log.Fatalf("Error when decode file: %s", err) return nil } return data } type RecipePath struct { Name string `json:"name"` Path string `json:"path"` } type CountryName struct { CountryID string `json:"countryId"` CountryName string `json:"countryName"` } func ScanRecipeFiles(countries []CountryName) map[string][]RecipePath { recipeFiles := map[string][]RecipePath{} for _, country := range countries { var files []string if country.CountryID == "thai" { files = ListFile("cofffeemachineConfig/coffeethai02_*.json") } else { files = ListFile("cofffeemachineConfig/" + country.CountryID + "/coffeethai02_*.json") } sort.Slice(files, func(i, j int) bool { file1, err := os.Stat(files[i]) if err != nil { log.Panic("Error when get file info:", err) } file2, err := os.Stat(files[j]) if err != nil { log.Panic("Error when get file info:", err) } return file1.ModTime().After(file2.ModTime()) }) for i := 0; i < len(files); i++ { if _, ok := recipeFiles[country.CountryID]; !ok { recipeFiles[country.CountryID] = []RecipePath{} } recipeFiles[country.CountryID] = append(recipeFiles[country.CountryID], RecipePath{ Name: filepath.Base(files[i]), Path: files[i], }) } } return recipeFiles }