package data import ( "encoding/json" "log" "os" "path/filepath" "recipe-manager/models" "sort" ) func readFile(version string) *models.Recipe { path := filepath.Join("cofffeemachineConfig", version) file, err := os.Open(path) 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 Data struct { CurrentVersion string AllVersions []string recipe *models.Recipe } func NewData() *Data { files, err := filepath.Glob("cofffeemachineConfig/coffeethai02_*.json") if err != nil { log.Panic("Error when scan recipe files:", err) } 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++ { files[i] = filepath.Base(files[i]) } return &Data{ CurrentVersion: "coffeethai02_580.json", AllVersions: files, recipe: readFile("coffeethai02_580.json"), } } func (d *Data) GetRecipe(version string) models.Recipe { if version == "" || version == d.CurrentVersion { return *d.recipe } log.Println("Change recipe to version:", version) // change current version and read new recipe d.CurrentVersion = version d.recipe = readFile(version) return *d.recipe } func (d *Data) GetRecipe01() []models.Recipe01 { return d.recipe.Recipe01 }