.

.

命令:cat test2.txt mygofile

https://beap.adss.yahoo.com/
https://id.answers.yahoo.com/search
https://brokenurl
https://id.answers.yahoo.com/KnowledgeSearchService
https://id.answers.yahoo.com/question/nextQuestion

样本URL的内容

package main

import (
    "log"
    "bufio"
    "bytes"
    "fmt"
    "net/http"
    "os"
    "strings"
    "crypto/tls"
)

func main() {
    tr := http.DefaultTransport.(*http.Transport).Clone()
    tr.TLSClientConfig = &tls.Config{InsecureSkipVerify: true}
    client := &http.Client{Transport: tr}

    passedUrl := bufio.NewScanner(os.Stdin)
    var pUrl string
    for passedUrl.Scan() {
        fmt.Println(passedUrl.Text())
        if strings.Contains(passedUrl.Text(), "://"){
            pUrl = passedUrl.Text()
        } else {
            pUrl = "https://" + passedUrl.Text()
        }

        body := "<?xml version=\"1.0\"?>"

        req, err := http.NewRequest("POST", pUrl, bytes.NewBuffer([]byte(body)))
        if err != nil {
            log.Println(err)
        }

        req.Header.Add("Content-Type", "application/xml; charset=utf-8")
        resp, err := client.Do(req)
        if err != nil {
            log.Println(err)
            continue // stop here and process next item
        }

        defer resp.Body.Close()

    }
}

问题是,当我给出一个巨大的URL列表时,代码非常慢。有什么办法可以让代码多线程化或以简单的方式更快。

解决方案:

创建worker goroutine池。 Worker goroutine从channel中获取要处理的urls,并在channel关闭时退出。主 goroutine 将 urls 输送到 channel,并在完成后关闭 channel。

tr := http.DefaultTransport.(*http.Transport).Clone()
tr.TLSClientConfig = &tls.Config{InsecureSkipVerify: true}
client := &http.Client{Transport: tr}

var wg sync.WaitGroup
work := make(chan string)
for i := 0; i < 10; i++ {
    wg.Add()
    go func() {
        defer wg.Done()
        for pUrl := range work {
            fmt.Println(purl)
            if !strings.Contains(purl, "://") {
                pUrl = "https://" + passedUrl.Text()
            }

            body := "<?xml version=\"1.0\"?>"

            req, err := http.NewRequest("POST", pUrl, strings.NewReader(body))
            if err != nil {
                log.Println(err)
                continue
            }

            req.Header.Add("Content-Type", "application/xml; charset=utf-8")
            resp, err := client.Do(req)
            if err != nil {
                log.Println(err)
                continue // stop here and process next item
            }

            // do something with resp

            resp.Body.Close()

        }
    }()
}

passedUrl := bufio.NewScanner(os.Stdin)
for passedUrl.Scan() {
    work <- passedUrl.Text()
}
close(work) // signal workers to exit
wg.Wait()   // wait for workers to exit

给TA打赏
共{{data.count}}人
人已打赏
解决方案

在SQL Server中,如果@RecCtr % 10000 =0,这条语句中的%号是什么功能或计算?

2022-4-20 1:00:10

解决方案

谷歌应用脚本在编码时不显示方法。

2022-4-20 1:00:12

0 条回复 A文章作者 M管理员
    暂无讨论,说说你的看法吧
个人中心
购物车
优惠劵
今日签到
有新私信 私信列表
搜索