// The Lookup function first looks for the given barcode in the barcodes // database. If not found there, it tries the Amazon Product API, and save // all those results into the barcodes database for future reference. It // returns the json (a list of API structs, one per product) and error. func Lookup(barcode string, asinLookup, asinInsert *sql.Stmt) ([]*commerce.API, error) { results := make([]*commerce.API, 0) var resultErr error // see if the barcode already exists in the db products, err := barcodes.LookupAsin(asinLookup, barcode) resultErr = err if err == nil && len(products) > 0 { for _, product := range products { result := new(commerce.API) result.SKU = product.Asin result.ProductName = product.ProductName result.ProductType = product.ProductType result.Vendor = strings.Join([]string{"AMZN", product.Locale}, ":") results = append(results, result) } } else { // if not, use the API instead, and save any results to the barcodes db api, aerr := apiLookup(barcode) resultErr = aerr if aerr == nil { // convert the api result string into a json object var apiList []commerce.API jerr := json.Unmarshal([]byte(api), &apiList) if jerr == nil { for _, apiResult := range apiList { // save each result for re-marshalling into json results = append(results, &apiResult) // and save it in the db, for the future prod := new(barcodes.AMAZON) prod.Barcode = barcode prod.Asin = apiResult.SKU prod.ProductName = apiResult.ProductName prod.ProductType = apiResult.ProductType vendor := strings.Split(apiResult.Vendor, ":") if len(vendor) > 0 { prod.Locale = vendor[1] } else { // use the default prod.Locale = "us" } _ = barcodes.InsertAsin(asinInsert, *prod) } } } } return results, resultErr }