为了账号安全,请及时绑定邮箱和手机立即绑定

golang 函数在切片长度超过 700 项时返回空切片

golang 函数在切片长度超过 700 项时返回空切片

Go
蝴蝶刀刀 2022-10-04 19:30:58
我有一个函数调用API来获取项目并返回项目以与另一个数据库同步。我可以指定返回的项目限制。如果限制为 700,则返回 700 个项目。如果超过 700,则返回空切片。func (d *dataBaseWriterImpl) WriteProducts() error {    username := os.Getenv("USERNAME")    password := os.Getenv("PASSWORD")    // get token    token, err := d.authService.Login(username, password)    if err != nil {        return err    }    // load products    // here the problem if count more than 700 <----    products, _ := d.scrapperService.LoadProducts(702, 1, token)    log.Printf("products count -> %d", len(products)) // gives me 0 <-----    errChan := make(chan error, 2)    var cats []models.Category    db.Conn.Model(&models.Category{}).Find(&cats)    var catIds []string    for _, cat := range cats {        catIds = append(catIds, cat.ExternalId)    }    for _, prod := range products {        if d.isValidProduct(catIds, prod.PrimaryVariant.CategoryID) {            log.Printf("update id -> %v", prod.PrimaryVariant.ID)            go d.saveOrUpdateProducts(prod.PrimaryVariant, errChan)        } else {            log.Printf("will not update id -> %v", prod.PrimaryVariant.ID)            go func() {                errChan <- nil            }()        }    }    for range products {        err := <-errChan        if err != nil {            return err        }    }    return nil}我记录项目长度,然后返回它返回 LoadProducts 实现中的实际值。func (s serviceImpl) LoadProducts(count uint, page uint, token string) ([]models.VariantsResult, error) {    jsonBody := []byte(fmt.Sprintf(`{"pageSize": %d, "page": %d, "sortBy": "updatedAt"}`, count, page))    body := bytes.NewBuffer(jsonBody)    // Create request    req, err := http.NewRequest("POST", fmt.Sprintf("%v/api/variantGroups/search", os.Getenv("BACKEND")), body)    if err != nil {        log.Print(err)    }   
查看完整描述

1 回答

?
蓝山帝景

TA贡献1843条经验 获得超7个赞

几乎可以肯定的是,您返回了错误,但随后忽略了它。


nil 切片的长度和容量为 0,并且没有基础数组。https://tour.golang.org/moretypes/12


你返回没有,错误在这里:


// in LoadProducts

if err != nil {

    return nil, err

}

但随后做


products, _ := d.scrapperService.LoadProducts(702, 1, token)

log.Printf("products count -> %d", len(products)) // gives me 0 <---

这应该是


products, err := d.scrapperService.LoadProducts(702, 1, token)

if err != nil {

    panic(err) // dont actually panic, but figure out what went wrong

}

log.Printf("products count -> %d", len(products)) // gives me 0 <---


查看完整回答
反对 回复 2022-10-04
  • 1 回答
  • 0 关注
  • 144 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号