我想做的是:
我想向此URL发送几个GET请求:
https://catalog.wb.ru/brands/m/catalog?page=1&limit=300&brand=5786&dest=-1257786&sort=pricedown
个
然后收集"产品"对象中的所有数据.键"Page"的值自动递增,以从所有页面获取数据.
实际上,我不太确定是否真的需要编写一个JSON来将其发送到前端.当我在for循环中得到新的响应时,发送不同的请求可能更好?
我做了什么:
做出了正确的 struct .对于单个请求,一切都运行得很好.
创建了requestBodyBytes []byte
和ProductsBytes []byte
,以便在它们后面加上ioutil.ReadAll
中的[]bytes
.
打印长度requestBodyBytes
我看到它随着每个请求而扩展,但是在我解组它之后,我在输出中看到了空的 struct .
我理解这种情况的发生是因为每一个请求我都会得到type Response
的新JSON.但是,如果我需要由来自几个JSON的type Response
个"产品"对象组成的Product structs
个切片怎么办?
注意:需要在for循环中初始化requestBodyBytes
才能使用它停止发送请求,因为当页面上没有信息时,服务器会给出200个代码和空的JSON.
提前谢谢您!
const URL = "https://catalog.wb.ru/brands/m/catalog?page=%d&limit=300&brand=5786&dest=-1257786&sort=pricedown"
type Response struct {
Data struct {
Products []Product `json:"products"`
} `json:"data"`
}
type Product struct {
ID int `json:"id"`
Name string `json:"name"`
Price int `json:"priceU"`
Rating float32 `json:"reviewRating"`
Sale int `json:"sale"`
New bool `json:"isNew"`
}
func main() {
var response Response
var products Response //Also tried to make it []Response
var ProductsBytes []byte
for i := 1; ; i++ {
resp, err := http.Get(fmt.Sprintf(URL, i))
if err != nil {
fmt.Printf("#1 Error: %s", err)
}
defer resp.Body.Close()
bytes, err := ioutil.ReadAll(resp.Body)
var requestBodyBytes []byte
requestBodyBytes = append(requestBodyBytes, bytes...)
ProductsBytes = append(ProductsBytes, bytes...)
json.Unmarshal(requestBodyBytes, &response)
fmt.Println(resp.Status)
fmt.Printf("\nSlice from page #%d\nLength of bytes: %d\n", i, len(bytes))
fmt.Printf("Length of finalResult: %d\n", len(requestBodyBytes))
if len(response.Data.Products) == 0 {
fmt.Println("There's no more data")
break
}
}
json.Unmarshal(ProductsBytes, &products)
fmt.Println(response)
fmt.Println(products)
fmt.Println(len(products))
}