I am new in Go. I'm trying to do scraper for the data from one my website, to be able to use it inside the Go app.
I using goroutines and sync.WaitGroup for waiting for results, but I have a problem. If I use goroutines and try to use json.Marshal for my dataset, I have empty array inside the structure, that is filling inside the goroutines.
If I am filling my structure without routines, I have everything working well.
Here are my structures:
type CategoryScrapper struct {
Name string `json:"name"`
Link string `json:"link"`
Products []Product.ProductData `json:"products"`
}
type ProductData struct {
Name string `json:"name"`
Link string `json:"link"`
Thumbnail string `json:"thumbnail"`
OriginPrice string `json:"OriginPrice"`
Excerpt string `json:"Excerpt"`
}
Here is a part of my app
func main() {
cs := Category.CategoryScrapper{
Name: "Name",
Link: "/link",
}
wg := new(sync.WaitGroup)
go cs.GetProducts(wg)
wg.Wait()
res, _ := json.Marshal(cs)
fmt.Println(string(res))
}
func (s *CategoryScrapper) GetProducts(pool *sync.WaitGroup) {
pool.Add(1)
defer pool.Done()
maxPageNum := s.getMaxPageNum()
localPool := new(sync.WaitGroup)
s.Products = make([]Product.ProductData, 0)
for i := 1; i <= maxPageNum; i++ {
go s.getPage(i, localPool)
}
localPool.Wait()
}
func (s *CategoryScrapper) getPage(page int, waitingPool *sync.WaitGroup) {
product := Product.ProductData{
Name: "Name",
Link: "Link",
Thumbnail: "Thumb",
OriginPrice: "1111",
Excerpt: "Excerpt",
}
s.Products = append(s.Products, product)
}