package main import ( "fmt" "math/rand" "os" "go.wit.com/log" ) // sent via -ldflags var VERSION string var BUILDTIME string var counter int = rand.Intn(100) func main() { var pb *Fruits pb = new(Fruits) if err := pb.loadBasket(); err != nil { log.Info("First time user?") } // attempt to load basket.pb fruit := &Fruit{ Brand: "mom", City: "New NewYork", UPC: "2000", } pb.Fruits = append(pb.Fruits, fruit) a := &Fruit{ Brand: "fry", City: "the moon", UPC: "2001", } pb.Fruits = append(pb.Fruits, a) b := pb.getNewFruit() pb.Fruits = append(pb.Fruits, b) pb.saveBasket() if err := pb.loadBasket(); err != nil { badExit(err) } pb.printTable() } func (pb *Fruits) addFruits(i int) { var x int for x < i { x += 1 b := pb.getNewFruit() pb.Fruits = append(pb.Fruits, b) } } func (pb *Fruits) getNewFruit() *Fruit { counter += rand.Intn(10) upc := fmt.Sprintf("%d", counter) a := &Fruit{ Brand: "fry", City: "the moon", UPC: upc, } return a } func (pb *Fruits) saveBasket() error { data, err := pb.Marshal() if err != nil { return err } w, err := os.OpenFile("basket.pb", os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0644) if err != nil { return err } w.Write(data) w.Close() log.Info("saved basket.pb ok") return nil } func badExit(err error) { log.Info("autogenpb error:", err) os.Exit(-1) } func (pb *Fruits) loadBasket() error { if pb == nil { pb = new(Fruits) } data, err := os.ReadFile("basket.pb") if err != nil { return err } if err := pb.Unmarshal(data); err != nil { return err } log.Info("loaded basket.pb ok") return nil } func (pb *Fruits) printTable() { var count int all := pb.All() for all.Scan() { tmp := all.Next() count += 1 log.Printf("found %d %s %s %s\n", count, tmp.Brand, tmp.City, tmp.UPC) if count > 10 { break } } log.Printf("Total entries: %d\n", pb.Len()) } func (pb *Fruits) sortTable(i int) { var count int all := pb.SortByBrand() for all.Scan() { tmp := all.Next() count += 1 log.Printf("found %d %s %s\n", count, tmp.Brand, tmp.City) if count > i { break } } log.Printf("Total entries: %d\n", pb.Len()) }