GoColly 中的默认模式是什么,同步还是异步?

What is the default mode in GoColly, sync or async?

GoColly默认执行网络请求的方式是什么?因为我们在收集器中有 Async 方法,所以我假设默认模式是同步的。 但是,当我在程序中执行这 8 个请求时,除了我需要使用 Wait 进行异步模式外,我没有发现任何特别的区别。似乎该方法仅控制程序的执行方式(其他代码)并且请求始终是异步的。

package main

import (
    "fmt"

    "github.com/gocolly/colly/v2"
)

func main() {

    urls := []string{
        "http://webcode.me",
        "https://example.com",
        "http://httpbin.org",
        "https://www.perl.org",
        "https://www.php.net",
        "https://www.python.org",
        "https://code.visualstudio.com",
        "https://clojure.org",
    }

    c := colly.NewCollector(
        colly.Async(true),
    )

    c.OnHTML("title", func(e *colly.HTMLElement) {
        fmt.Println(e.Text)
    })

    for _, url := range urls {

        c.Visit(url)
    }

    c.Wait()
}

默认集合同步的。

令人困惑的地方可能是收集器选项 colly.Async(),它忽略了实际参数。实际上在撰写本文时的实现是:

func Async(a ...bool) CollectorOption {
    return func(c *Collector) {
        c.Async = true // uh-oh...!
    }
}

基于this issue,这样做是为了向后兼容,所以(我相信)你可以传递一个没有参数的选项,它仍然有效,例如:

colly.NewCollector(colly.Async()) // no param, async collection

如果您完全删除异步选项并仅使用 colly.NewCollector() 进行实例化,网络请求将明显是连续的——即您也可以删除 c.Wait() 并且程序不会立即退出。