尝试在go中使用通道,但数据无法正确发送/接收到通道

  • 本文关键字:通道 数据 go http go channel
  • 更新时间 :
  • 英文 :


希望能够快速解析大量类似的url(只有一个'id'元素与下一个不同),并将响应体转储到稍后由main函数查询并用于构建文本文件的通道中。

getpageCanal()函数内部,主体似乎没问题,但在那之后,我不明白为什么通道不能正确加载主体字符串。

package main
import (
"fmt"
"io/ioutil"
"net/http"
"os"
)
func main() {
initial := "https://www1.medion.de/downloads/index.pl?op=detail&id="
ending := "&type=treiber&lang=uk"
links := []string{}
os.Remove("dump.txt")
dumpFile, _ := os.Create("dump.txt")
c := make(chan string)
for i := 16000; i < 16004; i++ {
links = append(links, initial+fmt.Sprint(i)+ending)
}
fmt.Println(links[0])
for _, link := range links {
//the hope is to make this a go routine, but first I need to just make it work
getpageCanal(c, link)
}
for el := range c {
fmt.Println(el)
n, err := dumpFile.WriteString(el)
if err != nil {
fmt.Println(err)
}
if n == 0 {
fmt.Println(" nothing written in main")
}
}
}
func getpageCanal(canal chan string, url string) {
defer close(canal)
page, err := http.Get(url)
if err != nil {
fmt.Println("you done fucked up, boy")
}
content, er2 := ioutil.ReadAll(page.Body)
//fmt.Println(content)
if er2 != nil {
fmt.Println(er2)
}
canal <- string(content)
}

按照第一个注释的指示修改代码后(每次调用后不关闭通道,并使对worker函数的调用成为go例程),我现在将为您提供一个工作版本:

package main
import (
"fmt"
"io/ioutil"
"net/http"
"os"
)
func main() {
initial := "https://www1.medion.de/downloads/index.pl?op=detail&id="
ending := "&type=treiber&lang=uk"
links := []string{}
os.Remove("dump.txt")
dumpFile, _ := os.Create("dump.txt")
c := make(chan string)
for i := 16000; i < 16004; i++ {
links = append(links, initial+fmt.Sprint(i)+ending)
}
fmt.Println(links[0])
for _, link := range links {
go getpageCanal(c, link)
}
for el := range c {
fmt.Println(el)
n, err := dumpFile.WriteString(el)
if err != nil {
fmt.Println(err)
}
if n == 0 {
fmt.Println(" nothing written in main")
}
}
}
func getpageCanal(canal chan string, url string) {
//defer close(canal)
page, err := http.Get(url)
if err != nil {
fmt.Println("you done fucked up, boy")
}
content, er2 := ioutil.ReadAll(page.Body)
//fmt.Println(content)
if er2 != nil {
fmt.Println(er2)
}
canal <- string(content)
}

相关内容

  • 没有找到相关文章

最新更新