这个问题困扰了我很长时间,我仍然无法弄清楚为什么会这样,请告诉我。
我正在运行一个函数,其中 goroutine 从源收集数据并将其组装成一个列表,该列表随后飞到等待该列表的管道。在所有这些过程之后,该函数返回通道。
刚拿到数据
package main
import (
"github.com/PuerkitoBio/goquery"
"net/http"
)
type (
TextField struct {
Selector string
}
GraphicField struct {
Selector string
Attribute string
}
Item struct {
InclusiveSelector string
TextFields []TextField
GraphicFields []GraphicField
}
Source struct {
Address string
ContentObject Item
}
)
func (s Source) DocumentProvidedSourceInformation() (*goquery.Document, error) {
r, err := http.Get(s.Address)
if err != nil {
return nil, err
}
document, err := goquery.NewDocumentFromReader(r.Body)
if err != nil {
return nil, err
}
defer r.Body.Close()
return document, nil
}
func (s Source) TheftLastItem(html *goquery.Document) <-chan []string {
var exhaustChannel chan []string
go func() {
var exhaustData []string
html.Find(s.ContentObject.InclusiveSelector).First().Each(
func(index int, item *goquery.Selection) {
for _, textField := range s.ContentObject.TextFields {
exhaustData = append(exhaustData, item.Find(textField.Selector).Text())
}
for _, graphicField := range s.ContentObject.GraphicFields {
graphicItem, presence := item.Find(graphicField.Selector).Attr(graphicField.Attribute)
if presence {
exhaustData = append(exhaustData, graphicItem)
}
}
exhaustChannel <- exhaustData
},
)
}()
return exhaustChannel
}
运行代码
package main
import "fmt"
func main() {
textFields := []TextField{
{
Selector: ".caption",
},
{
Selector: ".game-specs",
},
{
Selector: ".score",
},
}
graphicFields := []GraphicField{
{
Selector: ".image",
Attribute: "style",
},
}
game := Item{
InclusiveSelector: ".simple-list .item",
TextFields: textFields,
GraphicFields: graphicFields,
}
stopGame := Source{
Address: "https://stopgame.ru/games",
ContentObject: game,
}
document, err := stopGame.DocumentProvidedSourceInformation()
if err != nil {
fmt.Println(err)
}
for {
data := stopGame.TheftLastItem(document)
fmt.Println(<-data) // на этом моменте останавливается осуществление кода
}
}
通过试用(fmt.Println)我发现该函数本身可以正常工作,但是当我在启动过程中接收到数据并将其丢弃打印时,我的工作停止了。我立即启动了一个无限循环,因为这种实现将来会引起我的兴趣。但是如果你尝试运行一次,结果是一样的。
谁来初始化频道?