gpt4 book ai didi

curl - 在 Golang 中使用 curl 在网站上搜索字符串最有效和可扩展的等价物是什么?

转载 作者:IT王子 更新时间:2023-10-29 02:04:13 26 4
gpt4 key购买 nike

背景

user@host curl -s http://stackoverflow.com | grep -m 1 stackoverflow.com

如果找到字符串则立即返回:

<meta name="twitter:domain" content="stackoverflow.com"/>

瞄准

使用Golang在网站上查找字符串

方法

基于 Go by Example 的来源和 Schier's Blog创建了以下代码:

package main

import (
"fmt"
"io/ioutil"
"net/http"
"regexp"
)

func main() {
url := "http://stackoverflow.com"
resp, _ := http.Get(url)
bytes, _ := ioutil.ReadAll(resp.Body)
r, _ := regexp.Compile("stackoverflow.com")
fmt.Println(r.FindString(string(bytes)))
resp.Body.Close()
}

结果

运行代码结果:

stackoverflow.com

讨论与结论

  1. 需要更多代码才能在 Golang 中实现相同的目标,或者是否有更短的解决方案
  2. 两个选项似乎同时返回。在这种情况下,静态代码是否也比动态代码更快?
  3. 我担心这段代码是否占用过多内存。它最终应该被用来监控数百个不同的网站

最佳答案

此代码实现 grep,在包含给定字符串的第一行停止。它通过使用 bufio.Scanner 避免一次将整个网页读入内存,这除了限制内存使用外还可以在字符串位于接近开始处的情况下加速程序巨大的页面。请谨慎使用 scan.Bytes() 以避免将每一行都转换为字符串,这会导致显着的内存流失。

package main

import (
"bufio"
"bytes"
"fmt"
"log"
"net/http"
)

func main() {
resp, err := http.Get("http://stackoverflow.com")
if err != nil {
log.Fatalf("failed to open url")
}
scan := bufio.NewScanner(resp.Body)
toFind := []byte("stackoverflow.com")
defer resp.Body.Close()
for scan.Scan() {
if bytes.Contains(scan.Bytes(), toFind) {
fmt.Println(scan.Text())
return
}
}
}

关于curl - 在 Golang 中使用 curl 在网站上搜索字符串最有效和可扩展的等价物是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38447657/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com